1
--
拆分字符串的表值函数
2
3 alter Function f_Split
4 (
5 @Str Nvarchar ( max )
6 ) Returns @Re Table
7 (
8 Id int Identity , Val Nvarchar ( max )
9 )
10 As
11 Begin
12 Declare @Pos Int
13 Set @Pos = CharIndex (N ' , ' , @Str )
14 While @Pos > 0
15 Begin
16 Insert @Re Values ( Left ( @Str , @Pos - 1 ))
17 Select
18 @Str = Stuff ( @Str , 1 , @Pos , N '' ),
19 @Pos = CharIndex (N ' , ' , @Str )
20 End
21
22 If @Str > N ''
23 Insert @Re (Val) Values ( @Str )
24
25 Return
26 End
27 Go
28
29 Select * From dbo.f_Split(N ' hh,hello world,hyt ' )
2
3 alter Function f_Split
4 (
5 @Str Nvarchar ( max )
6 ) Returns @Re Table
7 (
8 Id int Identity , Val Nvarchar ( max )
9 )
10 As
11 Begin
12 Declare @Pos Int
13 Set @Pos = CharIndex (N ' , ' , @Str )
14 While @Pos > 0
15 Begin
16 Insert @Re Values ( Left ( @Str , @Pos - 1 ))
17 Select
18 @Str = Stuff ( @Str , 1 , @Pos , N '' ),
19 @Pos = CharIndex (N ' , ' , @Str )
20 End
21
22 If @Str > N ''
23 Insert @Re (Val) Values ( @Str )
24
25 Return
26 End
27 Go
28
29 Select * From dbo.f_Split(N ' hh,hello world,hyt ' )
正好csdn上有人问到相关的东西了,把这个函数稍加改进下
1
set
ANSI_NULLS
ON
2 set QUOTED_IDENTIFIER ON
3 go
4
5 Create Function [ dbo ] . [ f_Split ]
6 (
7 @Str Nvarchar ( max ),
8 @Spliter Nvarchar ( 2 )
9 ) Returns @Re Table
10 (
11 Id int Identity , Val Nvarchar ( max )
12 )
13 As
14 Begin
15 If @Spliter Is Null Or ( Len ( @Spliter ) = 0 )
16 Begin
17 Set @Spliter = N ' , '
18 End
19
20 Declare @Pos Int
21 Set @Pos = CharIndex ( @Spliter , @Str )
22 While @Pos > 0
23 Begin
24 Insert @Re Values ( Left ( @Str , @Pos - 1 ))
25 Select
26 @Str = Stuff ( @Str , 1 , @Pos , N '' ),
27 @Pos = CharIndex ( @Spliter , @Str )
28 End
29
30 If @Str > N ''
31 Insert @Re (Val) Values ( @Str )
32
33 Return
34 End
2 set QUOTED_IDENTIFIER ON
3 go
4
5 Create Function [ dbo ] . [ f_Split ]
6 (
7 @Str Nvarchar ( max ),
8 @Spliter Nvarchar ( 2 )
9 ) Returns @Re Table
10 (
11 Id int Identity , Val Nvarchar ( max )
12 )
13 As
14 Begin
15 If @Spliter Is Null Or ( Len ( @Spliter ) = 0 )
16 Begin
17 Set @Spliter = N ' , '
18 End
19
20 Declare @Pos Int
21 Set @Pos = CharIndex ( @Spliter , @Str )
22 While @Pos > 0
23 Begin
24 Insert @Re Values ( Left ( @Str , @Pos - 1 ))
25 Select
26 @Str = Stuff ( @Str , 1 , @Pos , N '' ),
27 @Pos = CharIndex ( @Spliter , @Str )
28 End
29
30 If @Str > N ''
31 Insert @Re (Val) Values ( @Str )
32
33 Return
34 End
欢迎加群互相学习,共同进步。QQ群:iOS: 58099570 | Android: 572064792 | Nodejs:329118122 做人要厚道,转载请注明出处!
本文转自张昺华-sky博客园博客,原文链接:http://www.cnblogs.com/sunshine-anycall/archive/2009/03/22/1418787.html
,如需转载请自行联系原作者