微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

SQLServer字符串批量拆分得方法

其实拆分和批量拆分的方法是一样的,所谓批量就是用out apply来调用单个拆分函数

 

 

/*
sqlServer字符串拆分函数,by jinjazz

--原始数据
id          names
----------- --------------------
1           jinjazz,blog,csdn
2           sql,ms

--生成的数据
id          rn          name
----------- ----------- ----------
1           1           jinjazz
1           2           blog
1           3           csdn
2           1           sql
2           2           ms


*/

set nocount on
use tempdb
go
if ( object_id ( 'f_test' ) is not null )
    drop function f_test
go
create function f_test (@ a varchar ( max ))
returns @ t table ( rn int , v varchar ( max ))
as
begin
    insert into @ t
    select b . * from (
    select convert ( xml , '<v>' + replace (@ a , ',' , '</v><v>' ) + '</v>' ) as f ) a
    outer apply
    (
        SELECT rn = row_number () over ( order by getdate ()), t . c . value ( '.' , 'varchar(max)' ) AS f
                 FROM a . f . nodes ( '//v' ) AS t ( c )
    )b   
    return
end
go


declare @ t table ( id int , names varchar ( 20 ))
insert into @ t select 1 , 'jinjazz,csdn'
insert into @ t select 2 , 'sql,ms'

select * from @ t
select a . id , rn , b . v as name from @ t a outer apply dbo . f_test ( a . names ) b

set nocount off

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐