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


*/

setnocounton
usetempdb
go
if (object_id ('f_test' ) isnotnull )
     dropfunctionf_test
go
createfunctionf_test (@avarchar (max ))
returns @ttable (rnint , vvarchar (max ))
as
begin
    insertinto @t
    select b. *from (
     selectconvert (xml , '<v>' + replace (@a , ',' , '</v><v>' )+ '</v>' ) asf )a
     outerapply
    (
         SELECTrn = row_number ()over (orderbygetdate ()),t . c . value ('.' , 'varchar(max)' ) ASf
                  FROMa . f . nodes ('//v' ) ASt (c )
     )b   
    return
end
go


declare @ttable (idint , namesvarchar (20 ))
insertinto @tselect1 , 'jinjazz,blog,csdn'
insertinto @tselect2 , 'sql,ms'

select*from @t
selecta . id , rn , b. vasnamefrom @taouterapplydbo . f_test (a . names ) b

setnocountoff


本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/jinjazz/archive/2009/08/27/4490912.aspx

posted @ 2022-12-03 09:15  星火燎猿*  阅读(191)  评论(0编辑  收藏  举报