以前记得有这么一个方法,但是找不到了 所以只好自己写一个了
sql中使用指定字符分离长字符串,并以table形式输出
例子
select * from SplitString('abc,aadd,asdf,,asdf,,asdf',',')
结果
substr
------------------------------------------------------------------------------------------------------------------------abc
aadd
asdf
asdf
asdf
(5 row(s) affected)
--------------------------------------
方法代码
-----------------
Create FUNCTION SplitString
(
@string as nvarchar(2048),
@split as nvarchar(50)
)
RETURNS @reports TABLE(substr nvarchar(2048))
AS
begin
declare @start_location as int
declare @begin as int
declare @end as int
declare @substr as nvarchar(255)
set @start_location=0
while(len(@string)>0)
begin
select @begin=Charindex(@split,@string,@start_location)
select @end=Len(@split)
if(@begin>0)
begin
select @substr = Substring(@string,0,Charindex(@split,@string,@start_location))
select @string = Substring(@string,@begin+@end,len(@string))
end
else
begin
select @substr=@string
select @string='';
end
if(@substr!='')
insert @reports select @substr
end
RETURN
end
--------------------------------
没有评论:
发表评论