SQL Server字符串切割
1 CREATE FUNCTION fGetStrBySplit
2 (
3 @Source VARCHAR(max),
4 @Index INT,
5 @SplitChar VARCHAR(1)
6 )
7 RETURNS varchar(MAX)
8 AS
9 BEGIN
10
11 DECLARE @Len INT
12 DECLARE @n INT = 0
13 DECLARE @ChIndex INT
14 DECLARE @Result VARCHAR(MAX)
15 --获取总长度
16 SET @Len = LEN(@Source)
17 --获取切割字符位置
18 SET @ChIndex = CHARINDEX(@SplitChar,@Source)
19
20 WHILE @ChIndex > 0
21 BEGIN
22 IF(@n = @Index)
23 BEGIN
24 SET @Source = SUBSTRING(@Source,0,@ChIndex)
25 BREAK
26 END
27
28 SET @Source = SUBSTRING(@Source,@ChIndex+1,@Len)
29 SET @ChIndex = CHARINDEX(@SplitChar,@Source)
30
31 SET @Len = LEN(@Source)
32 SET @n = @n + 1
33
34 END
35
36 RETURN @Source
37 END
38 GO
39
40 --调用
41 DECLARE @value VARCHAR(max)
42 SET @value = dbo.fGetStrBySplit('645002*01_45854_183677_12',0,'_')
43 PRINT @value
2 (
3 @Source VARCHAR(max),
4 @Index INT,
5 @SplitChar VARCHAR(1)
6 )
7 RETURNS varchar(MAX)
8 AS
9 BEGIN
10
11 DECLARE @Len INT
12 DECLARE @n INT = 0
13 DECLARE @ChIndex INT
14 DECLARE @Result VARCHAR(MAX)
15 --获取总长度
16 SET @Len = LEN(@Source)
17 --获取切割字符位置
18 SET @ChIndex = CHARINDEX(@SplitChar,@Source)
19
20 WHILE @ChIndex > 0
21 BEGIN
22 IF(@n = @Index)
23 BEGIN
24 SET @Source = SUBSTRING(@Source,0,@ChIndex)
25 BREAK
26 END
27
28 SET @Source = SUBSTRING(@Source,@ChIndex+1,@Len)
29 SET @ChIndex = CHARINDEX(@SplitChar,@Source)
30
31 SET @Len = LEN(@Source)
32 SET @n = @n + 1
33
34 END
35
36 RETURN @Source
37 END
38 GO
39
40 --调用
41 DECLARE @value VARCHAR(max)
42 SET @value = dbo.fGetStrBySplit('645002*01_45854_183677_12',0,'_')
43 PRINT @value