转自http://www.shangxueba.com/jingyan/1940447.html
1.游标方式
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: <Author,,Name>
-- Create date: <Create Date,,>
-- Description: <Description,,>
-- =============================================
create PROCEDURE InsertCheckItemCategory
-- Add the parameters for the stored procedure here
@levelCode INT
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
DECLARE @newCategoryId UNIQUEIDENTIFIER
DECLARE @oldCategoryId NVARCHAR(50)
DECLARE @childLevelCode INT
SET @childLevelCode=@levelCode+1
DECLARE data_cursor CURSOR
FOR
( SELECT CheckItemCategory.Id AS newCategoryId ,
AppCheckItem.Id AS oldCategoryId
FROM CheckItemCategory
LEFT JOIN AppCheckItem ON CheckItemCategory.Descr = AppCheckItem.[Text]
WHERE LevelCode = @levelCode
) --使用游标的对象(跟据需要填入select文)
OPEN data_cursor --打开游标
FETCH NEXT FROM data_cursor INTO @newCategoryId, @oldCategoryId --将游标向下移1行,获取的数据放入之前定义的变量@id,@name中
WHILE @@fetch_status = 0 --判断是否成功获取数据
BEGIN
--进行相应处理(跟据需要填入SQL文)
INSERT INTO dbo.CheckItemCategory
( Id ,
Descr ,
OrderNo ,
LevelCode ,
ParentId ,
CreatedTime ,
UpdatedTime ,
IsDeleted
)
SELECT NEWID() ,
AppCheckItem.[Text] AS Descr ,
ROW_NUMBER() OVER(ORDER BY Id ASC) AS RowNumber,
@childLevelCode ,
@newCategoryId ,
GETDATE() ,
GETDATE() ,
0
FROM AppCheckItem
WHERE ParentId = @oldCategoryId AND Title=1
FETCH NEXT FROM data_cursor INTO @newCategoryId,
@oldCategoryId --将游标向下移1行
END
CLOSE data_cursor --关闭游标
DEALLOCATE data_cursor
END
GO
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
如果是简单单表批量插入操作的,上面方法大可不必要