SQL F_Split函数

 f_split函数把“逗号分隔的列值” 转换成表记录,可用于in、exist做关联查询。

 f_split函数:

--==========================================
-- created by: mark.yang
-- create date: 2016-8-2
-- description: f_split函数把“逗号分隔的列值” 转换成表记录
-- test: select * from F_Split(u.groupID,',')
--========================================
create function [dbo].[F_Split](@SourceSql varchar(8000),@StrSeprate varchar(10))

returns @temp table(id int, value varchar(100))
as
BEGIN
    --第一种写法
    declare @i int,@j int
    set @SourceSql=rtrim(ltrim(@SourceSql))
    set @i=charindex(@StrSeprate,@SourceSql)
    set @j=0
    while @i>=1
    begin       
        insert @temp values( @j+1,left(@SourceSql,@i-1))
        set @SourceSql=substring(@SourceSql,@i+1,len(@SourceSql)-@i)
        set @i=charindex(@StrSeprate,@SourceSql)
        set @j=@j+1
    end
    if @SourceSql<>''
       insert @temp values(@i,@SourceSql)
    return
    --第二种写法
     /* while(charindex(@split,@c)<>0)
        BEGIN
        insert @t(col) values (substring(@c,1,charindex(@split,@c)-1))
        set @c = stuff(@c,1,charindex(@split,@c),'')
        end
        insert @t(col) values (@c)
        Delete From @t Where ISNULL(col,'')=''
        return */
end

GO

 

posted @ 2016-08-02 14:22  Mark.Yang  阅读(2813)  评论(0编辑  收藏  举报