存储过程中实现类似split功能(charindex)
1create procedure sp_split_string
2(
3 @string NVARCHAR(4000)
4)
5AS
6BEGIN
7 DECLARE @object_id nvarchar(500)
8 DECLARE @i INT
9 DECLARE @len INT
10 print @string
11 IF (@string IS NULL) OR (LTRIM(@string) = '')
12 RETURN
13
14 WHILE CHARINDEX(',',@string) > 0
15 BEGIN
16 SET @len = LEN(@string)
17 SET @i = CHARINDEX(',', @string)
18 SET @object_id = LEFT(@string, @i-1)
19
20 INSERT INTO a (id) VALUES (@object_id)--少做修改,改成需要的sql语句即可
21 SET @string = RIGHT(@string, @len - @i)
22 END
23 SET @object_id = @string
24 INSERT INTO a (id) VALUES (@object_id)--少做修改,改成需要的sql语句即可
25END
26go
27
28--测试
29-- select * from a
30-- exec sp_split_string '102,103,105,106,107,108,200,500,306,408'
31-- select * from a
2(
3 @string NVARCHAR(4000)
4)
5AS
6BEGIN
7 DECLARE @object_id nvarchar(500)
8 DECLARE @i INT
9 DECLARE @len INT
10 print @string
11 IF (@string IS NULL) OR (LTRIM(@string) = '')
12 RETURN
13
14 WHILE CHARINDEX(',',@string) > 0
15 BEGIN
16 SET @len = LEN(@string)
17 SET @i = CHARINDEX(',', @string)
18 SET @object_id = LEFT(@string, @i-1)
19
20 INSERT INTO a (id) VALUES (@object_id)--少做修改,改成需要的sql语句即可
21 SET @string = RIGHT(@string, @len - @i)
22 END
23 SET @object_id = @string
24 INSERT INTO a (id) VALUES (@object_id)--少做修改,改成需要的sql语句即可
25END
26go
27
28--测试
29-- select * from a
30-- exec sp_split_string '102,103,105,106,107,108,200,500,306,408'
31-- select * from a