sqlserver分割字串並轉行

2021-10-07 14:43:44 字數 2612 閱讀 3109

插入測試資料

create

table test(name nvarchar(

100)

,class nvarchar(

100)

,[description] nvarchar(

100)

)insert

into test

select

'張三;李四'

,'一二班'

,'小學'

union

allselect

'王五'

,'一三班'

,'小學'

union

allselect

null

,'一四班'

,'中學'

union

allselect

'王二麻子;阿貓;阿狗'

,'一五班'

,'中學'

select

*from test

結果如下

想要的結果是

引用網上的乙個function(

alter

function

[dbo]

.[splitl]

(@string

varchar

(max)

,@delimiter

varchar

(max)

)returns

@temptable

table

(items varchar

(max))as

begin

declare

@idx

int=

1declare

@slice

varchar

(max)

iflen

(@string

)<1or

len(isnull(

@string,''

))=0

return

while

@idx!=0

begin

set@idx

= charindex(

@delimiter

,@string)if

@idx!=0

set@slice

=left

(@string

,@idx-1

)else

set@slice

=@string

iflen

(@slice

)>

0insert

into

@temptable

(items)

values

(@slice

)set

@string

=right

(@string

,len

(@string)-

@idx)if

len(

@string)=

0break

endreturn

end

select

*from splitl(

(select

top1 name from test)

,';'

)

效果如下

最終**

with tmp 

as(select row_number(

)over

(order

by name) num,

*,isnull(name,

'a;'

) name1

from test a)

select

case b.items when

'a'then

null

else b.items end name,a.class, a.description

from tmp a

cross

(select

*from splitl(

(select name1 from tmp where num=a.num)

,';'))

as b

空的先給他賦個值』a;』,然後再替換成null,不然空的那行會被過濾

如果沒有null,可以這樣寫

Sqlserver 字串分割

字串分割,返回字串按指定分割符分割後長度 使用 select dbo.fun get strarraylength 1,2,3,4 create function dbo fun get strarraylength str varchar 1024 要分割的字串 split varchar 10 ...

SQL SERVER分割字串

1 使用指定的字串分割,返回分割後元素的個數 create function get strlength str varchar 1024 split varchar 10 returns int asbegin declare location int declare start int decl...

sqlserver 字串分割函式

create function split charstring nvarchar 4000 字串 separator char 1 分割符 returns tb temp table string nvarchar 4000 asbegin declare beginindex int,separ...