/*
****拆分一个字符串*********
问题描述:
@str='fds,bbbf,eee,ddd,fff,hhhfg,dddde' 拆分成
col
------------------------
fds
bbbf
eee
ddd
fff
hhhfg
dddde
*/
---方法:动态
declare @str varchar(500),@aaa varchar(8000)
set @str='fds,bbbf,eee,ddd,fff,hhhfg,dddde'
set @aaa='select * from (select '''+REPLACE(@str,',',''' as str union all select ''')+''') a '
exec(@aaa)
go
--方法:循环
create table #t(
id varchar(10))
declare @str varchar(300)
set @str='fds,bbbf,eee,ddd,fff,hhhfg,dddde'
declare @i int
declare @len int
set @i = 1
while @i < len(@str+',')
begin
insert #t select substring(@str+',',@i,charindex(',',@str+',',@i)-@i)
set @i = charindex(',',@str+',',@i)+1
end
select * from #t
drop table #t
go
--or
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
--方法:使用临时性分拆辅助表法
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
declare @str varchar(500),@aaa varchar(8000)
set @str='fds,bbbf,eee,ddd,fff,hhhfg,dddde'
select * from dbo.f_splitSTR(@str,',')
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/feixianxxx/archive/2010/01/27/5263341.aspx