sqlserver字串拆分(split)方法彙總

iteye_20954發表於2011-12-31
--方法0:動態SQL法 declare @s varchar(100),@sql varchar(1000) set @s='1,2,3,4,5,6,7,8,9,10' set @sql='select col='''+ replace(@s,',',''' union all select ''')+'''' PRINT @sql exec (@sql) if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[f_splitSTR]') and xtype in (N'FN', N'IF', N'TF')) drop function [dbo].[f_splitSTR] GO --方法1:迴圈擷取法 CREATE FUNCTION f_splitSTR( @s varchar(8000), --待分拆的字串 @split varchar(10) --資料分隔符 )RETURNS @re TABLE(col varchar(100)) AS BEGIN DECLARE @splitlen int SET @splitlen=LEN(@split+'a')-2 WHILE CHARINDEX(@split,@s)>0 BEGIN INSERT @re VALUES(LEFT(@s,CHARINDEX(@split,@s)-1)) SET @s=STUFF(@s,1,CHARINDEX(@split,@s)+@splitlen,'') END INSERT @re VALUES(@s) RETURN END GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[f_splitSTR]') and xtype in (N'FN', N'IF', N'TF')) drop function [dbo].[f_splitSTR] GO --方法2:使用臨時性分拆輔助表法 CREATE FUNCTION f_splitSTR( @s varchar(8000), --待分拆的字串 @split varchar(10) --資料分隔符 )RETURNS @re TABLE(col varchar(100)) AS BEGIN --建立分拆處理的輔助表(使用者定義函式中只能操作表變數) DECLARE @t TABLE(ID int IDENTITY,b bit) INSERT @t(b) SELECT TOP 8000 0 FROM syscolumns a,syscolumns b INSERT @re SELECT SUBSTRING(@s,ID,CHARINDEX(@split,@s+@split,ID)-ID) FROM @t WHERE ID<=LEN(@s+'a') AND CHARINDEX(@split,@split+@s,ID)=ID RETURN END GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[f_splitSTR]') and xtype in (N'FN', N'IF', N'TF')) drop function [dbo].[f_splitSTR] GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[tb_splitSTR]') and objectproperty(id,N'IsUserTable')=1) drop table [dbo].[tb_splitSTR] GO --方法3:使用永久性分拆輔助表法 --字串分拆輔助表 SELECT TOP 8000 ID=IDENTITY(int,1,1) INTO dbo.tb_splitSTR FROM syscolumns a,syscolumns b GO --字串分拆處理函式 CREATE FUNCTION f_splitSTR( @s varchar(8000), --待分拆的字串 @split varchar(10) --資料分隔符 )RETURNS TABLE AS RETURN( SELECT col=CAST(SUBSTRING(@s,ID,CHARINDEX(@split,@s+@split,ID)-ID) as varchar(100)) FROM tb_splitSTR WHERE ID<=LEN(@s+'a') AND CHARINDEX(@split,@split+@s,ID)=ID) GO --方法4:利用sql server2005的OUTER APPLY CREATE FUNCTION [dbo].[fn_Split] ( @str VARCHAR(MAX) , @split VARCHAR(10) ) RETURNS TABLE AS RETURN ( SELECT B.id FROM ( SELECT [value] = CONVERT(XML , '<v>' + REPLACE(@str , @split , '</v><v>') + '</v>') ) A OUTER APPLY ( SELECT id = N.v.value('.' , 'varchar(100)') FROM A.[value].nodes('/v') N ( v ) ) B ) 備註說明: 方法4必須在sql server2005下才可以執行

——————————————————————————————————————————

在本人看來, 方法4最值得使用。

Example:

SELECT id FROM fn_Split('a,b,d,c',',')




相關文章