SQL - 使用select语句和循环来填充存储过程

时间:2014-12-15 12:42:40

标签: sql-server sql-server-2008 stored-procedures

我必须使用存储过程来更新某些字段。 sp看起来像这样:

exec dbo.spMaintainConditionComponent
@Mask = 16
,@ConditionComponentUID = 
   ,@Status = 1
   ,@ArchiveUser = ''
   ,@ArchiveDate = ''
   ,@ArchiveReason = 'Removed'
   ,@ArchiveTypeID = '464'

除了可以从这个选择代码中获得的@ConditionComponentUID之外,所有参数都具有相同的值:

SELECT     tbConditionComponent.ConditionComponentUID
FROM         tbAsset INNER JOIN
                  tbConditionComponent ON tbAsset.AssetUID = tbConditionComponent.ParentID
WHERE     (tbAsset.Status = 1)

我还需要使用' while循环'或者'光标'因为多个记录不能同时更新。请有人帮忙吗?

1 个答案:

答案 0 :(得分:1)

有许多方法可以更新数据。最糟糕的是'通过使用循环'。如果您没有任何其他选择使用光标通过值循环:

DECLARE LoopCursor CURSOR FOR
        SELECT tbConditionComponent.ConditionComponentUID
        FROM tbAsset INNER JOIN tbConditionComponent ON tbAsset.AssetUID = tbConditionComponent.ParentID
        WHERE (tbAsset.Status = 1)

DECLARE @ConditionComponentUIDTemp AS UNIQUEIDENTIFIER

    OPEN LoopCursor
    FETCH NEXT FROM LoopCursor INTO @ConditionComponentUIDTemp

    WHILE @@FETCH_STATUS = 0
    BEGIN
        exec dbo.spMaintainConditionComponent
        @Mask = 16
        ,@ConditionComponentUID = @ConditionComponentUIDTemp
        ,@Status = 1
        ,@ArchiveUser = ''
        ,@ArchiveDate = ''
        ,@ArchiveReason = 'Removed'
        ,@ArchiveTypeID = '464'

        FETCH NEXT FROM LoopCursor INTO @ConditionComponentUIDTemp
    END

CLOSE LoopCursor
DEALLOCATE LoopCursor