首頁 >資料庫 >mysql教程 >SQLSplit拆分字符串

SQLSplit拆分字符串

WBOY
WBOY原創
2016-06-07 14:57:062351瀏覽

SQLServer拆分字符串到临时表 无 GOCreate function [dbo].[split](@SourceSql varchar(max),@StrSeprate varchar(10))returns @temp table(line varchar(max))asbegin declare @i int set @SourceSql = rtrim(ltrim(@SourceSql)) set @i = charindex(@StrSep

SQLServer拆分字符串到临时表 SQLSplit拆分字符串
GO
Create function [dbo].[split]
(
@SourceSql varchar(max),
@StrSeprate varchar(10)
)
returns @temp table(line varchar(max))
as
begin
    declare @i int
    set @SourceSql = rtrim(ltrim(@SourceSql))
    set @i = charindex(@StrSeprate,@SourceSql)
    while @i >= 1
    begin
        if len(left(@SourceSql,@i-1))>0
        begin
            insert @temp values(left(@SourceSql,@i-1))
        end
        set @SourceSql=substring(@SourceSql,@i+len(@StrSeprate),len(@SourceSql)-@i)
        set @i=charindex(@StrSeprate,@SourceSql)
    end
    if @SourceSql <> ''
        insert @temp values(@SourceSql)
    return
end

-----测试
GO
Select * From dbo.split('asd,f,gh,jk,l',',')
--SQL 递归
Create function [dbo].[split]
(
@SourceSql varchar(max),
@StrSeprate varchar(10)
)
returns @temp table(line varchar(max))
as
begin
	;with roy as 
	(
		select COl2=cast(substring(@SourceSql+@StrSeprate,1,charindex(@StrSeprate,@SourceSql+@StrSeprate)-1) as nvarchar(max)),
		Split=cast(substring(@SourceSql+@StrSeprate,charindex(@StrSeprate,@SourceSql+@StrSeprate)+1,len(@SourceSql+@StrSeprate)-charindex(@StrSeprate,@SourceSql+@StrSeprate)) as varchar(max))
	union all
		select COl2=cast(cast(substring(Split,1,charindex(@StrSeprate,Split)-1) as nvarchar(100)) as nvarchar(max)),
		Split= cast(substring(Split,charindex(@StrSeprate,Split)+1,len(Split)-charindex(@StrSeprate,Split)) as varchar(max))
		from Roy where charindex(@StrSeprate,Split)>1
	)
	Insert into @temp(line)select COl2 from roy option (MAXRECURSION 0)
    return
end
陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn