T-SQL on the string processing capabilities are relatively weak, such as I want to loop traversal like 1, 2, 3, 4, 5 such strings, if the use of arrays, traversal is very simple, but the T-SQL does not support the array, so it is troublesome to handle it. The following function implements string processing like an array.
1. Split the string by the specified symbol and return the number of elements after the split. The method is very simple, that is, to check the number of separators in the string, and then add one, which is the required result.
-
- Create FunctionGet_strarraylength
-
- (
-
- @ STR varchar (1024 ),-- String to be split
-
- @ Split varchar (10)-- Separator
-
- )
-
- Returns int
-
- As
-
- Begin
-
- Declare@ Location int
- Declare@StartInt
-
- Declare@LengthInt
-
-
-
- Set@ STR =Ltrim(Rtrim(@ Str ))
-
- Set@ Location = charindex (@ split, @ Str)
-
- Set@Length= 1
-
- While@ Location <> 0
-
- Begin
-
- Set@Start= @ Location + 1
- Set@ Location = charindex (@ split, @ STR ,@Start)
-
- Set@Length= @Length+ 1
-
- End
-
- Return@Length
-
- End
Call example: Select DBO. get_strarraylength ('78, 1, 2, 3 ',',')
Return Value: 4
2. Split the string by the specified symbol and return the nth element of the specified index after the split, which is as convenient as an array.
-
- Create FunctionGet_strarraystrofindex
-
- (
-
- @ STR varchar (1024 ),-- String to be split
- @ Split varchar (10 ),-- Separator
-
- @IndexInt-- Take the nth Element
-
- )
-
- Returns varchar (1024)
-
- As
-
- Begin
-
- Declare@ Location int
-
- Declare@StartInt
-
- Declare@ Next int
-
- Declare@ Seed int
-
-
- Set@ STR =Ltrim(Rtrim(@ Str ))
-
- Set@Start= 1
-
- Set@ Next = 1
-
- Set@ Seed = Len (@ split)
-
-
-
- Set@ Location = charindex (@ split, @ Str)
-
- While@ Location <> 0And@Index> @ Next
-
- Begin
-
- Set@Start= @ Location + @ Seed
- Set@ Location = charindex (@ split, @ STR ,@Start)
-
- Set@ Next = @ next + 1
-
- End
-
- If@ Location = 0Select@ Location = Len (@ Str) + 1
-
- -- There are two cases: 1. There is no Separator in the string. 2. There is a separator in the string. After jumping out of the while loop, @ location is 0, by default, there is a separator behind the string.
-
-
-
- ReturnSubstring (@ STR ,@Start, @ Location -@Start)
-
- End
Call example: Select DBO. get_strarraystrofindex ('8, 9, 4', ',', 2)
Return Value: 9
3. Combine the above two functions to traverse the elements in the string like an array
- Declare@ STR varchar (50)
- Set@ STR ='1, 2, 3, 4, 5'
- Declare@ Next int
- Set@ Next = 1
- While@ Next <= DBO. get_strarraylength (@ STR,',')
- Begin
- Print DBO. get_strarraystrofindex (@ STR,',', @ Next)
- Set@ Next = @ next + 1
- End
Call result:
1
2
3
4
5
http: // www.616.cn HTTP: // game.616.cn
flex web board game, video conversion software, crawlers are welcome to buy them! Slide the internet!