代码如下:
.游标方式 1 DECLARE @Data NVARCHAR(max)
SET @Data='1,tanw;2,keenboy' --Id,NameDECLARE @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/*
在这里做逻辑处理,插入或更新操作 ...
*/
ENDCLOSE data_cursor
DEALLOCATE data_cursor
SET @Data='1,tanw;2,keenboy' --Id,NameDECLARE @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/*
在这里做逻辑处理,插入或更新操作 ...
*/
ENDCLOSE data_cursor
DEALLOCATE data_cursor
代码如下:
.While方式
DECLARE @Data NVARCHAR(max)
SET @Data='tanw,NameDECLARE @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
DECLARE @Data NVARCHAR(max)
SET @Data='tanw,NameDECLARE @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
如果是简单单表批量插入操作的,上面方法大可不必要