剛好是工作上遇到需要傳入多個ID字串給SP,
然後SP會根據"逗點"自動將傳入的字串切割。(如下方範例)
[EX:]
EXEC @return_value = [dbo].[Split] @Data_ID_Str = N'N123456789,A123456789,C123456789'
CREATE PROCEDURE [dbo].[Split] @OldStr nvarchar(1500)/*原始字串*/ @splitStr varchar(50) /*分割字元*/ AS IF OBJECT_ID('tempdb..'+'#Return_Table') is not NULL DROP TABLE #Return_Table Create table #Return_Table ([word] varchar(20) NULL,[Data_id] varchar(18),[Data_ID_VerNo] int,Proc_Status_CD char(3),Insured_Cust_No int) set @splitStr=','/*以','為分割字元*/ set @OldStr=@Data_ID_Str Declare @TempStr varchar(20) WHILE (CHARINDEX(@splitStr,@OldStr)>0)/*就一直執行迴圈直到字串@OldStr沒有','*/ BEGIN Set @TempStr=SUBSTRING(@OldStr,1,CHARINDEX(@splitStr,@OldStr)-1)/*取出最前面的@OldStr*/ Insert into #Return_Table (word) Values (@TempStr) Set @OldStr = REPLACE(@OldStr,@TempStr+@splitStr,'')/*把最前面的被切割字串加上分割字元後,取代為空字串再指派回給@OldStr*/ END/*End While*/ IF(LEN(RTRIM(LTRIM(@OldStr)))>0 And CHARINDEX(@splitStr,RTRIM(LTRIM(@OldStr)))=0) /*@OldStr有值但沒有分割字元,表示此為最後一個要被切割的字串*/ Begin Set @TempStr=@OldStr /*取出word*/ Insert into #Return_Table (word) Values (@TempStr) End /*End IF*/ END