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
/*
在這裡做邏輯處理,插入或更新操作 ...
www.jb51.net
*/
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+','
www.jb51.net
/*
在這裡做邏輯處理,插入或更新操作 ...
*/
END
SELECT @Results
如果是簡單單表批量插入操作的,上面方法大可不必要
作者 keenboy