For SQL statements, it is troublesome to operate the set type (one row per row). In general, systems or projects with complicated business logic involve the issue of collection traversal, usually some people want to use cursors. Here I list two solutions for your reference.
For SQL statements, it is troublesome to operate the set type (one row per row). In general, systems or projects with complicated business logic involve the issue of collection traversal, usually some people want to use cursors. Here I list two solutions for your reference.
1. cursor Mode
The Code is as follows:
DECLARE @ Data NVARCHAR (max)
SET @ Data = '1, tanw, 2, keenboy '-- Id, Name
DECLARE @ dataItem NVARCHAR (100)
DECLARE data_cursor cursor for (SELECT * FROM split (@ Data ,';'))
OPEN data_cursor
Fetch next from data_cursor INTO @ dataItem
WHILE @ FETCH_STATUS = 0
BEGIN
DECLARE @ Id INT
DECLARE @ Name NVARCHAR (50)
DECLARE dataItem_cursor cursor for (SELECT * FROM split (@ dataItem ,','))
OPEN dataItem_cursor
Fetch next from dataItem_cursor INTO @ Id
Fetch next from dataItem_cursor INTO @ Name
CLOSE dataItem_cursor
DEALLOCATE dataItem_cursor
/*
Perform logical processing, insert, or update operations here...
Www.jb51.net
*/
END
CLOSE data_cursor
DEALLOCATE data_cursor
2. While Mode
The Code is as follows:
DECLARE @ Data NVARCHAR (max)
SET @ Data = 'tanw, keenboy '-- Id, Name
DECLARE @ Temp TABLE
(
Id int identity (1, 1 ),
Name NVARCHAR (50)
)
DECLARE @ Id INT
DECLARE @ Name NVARCHAR (50)
DECLARE @ Results NVARCHAR (MAX) SET @ Results =''
Insert into @ Temp SELECT (SELECT * FROM split (@ Data ,';'))
While exists (SELECT * FROM @ Temp)
BEGIN
Select top 1 @ Id = Id, @ Name = Name from @ Temp
Delete from @ Temp where [id] = @ Id
SET @ Results = @ Results + @ Name + ','
Www.jb51.net
/*
Perform logical processing, insert, or update operations here...
*/
END
SELECT @ Results
For a simple single table batch insert operation, the above method is not required
Author keenboy