1、游标方式
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
/*
这里做逻辑处理,插入或更新操作等
*/
END
CLOSE data_cursor
DEALLOCATE data_cursor
2、While方式
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+','
/*
这里做逻辑处理,插入或更新操作等
*/
END
SELECT @Results
注意,以上代码不适合简单的单表批量插入,因为这样的操作一句sql就搞定了,无需这么大的工程,呵呵。