使用游标更新表?

时间:2011-01-31 20:56:16

标签: sql sql-server-2008

更新

这个例外的目的是消除@RegModifiedDateTime再次传递我想要的东西,我应该能够通过传递ModifiedDateTime来阅读Id

示例:如果我通过Id = 564,那么我应该能够阅读

`schoold_Id and ModifiedDateTime`

结束更新

这是我的表格对于SchoolRegistration的看法:

school_id       id     active        modifydatetime
--------------------------------------------------
432        564       1               2008-12-14 13:15:38.750
342        564       1              2008-12-14 14:15:50.470
353        564       1              2008-12-14 14:19:46.703

结束更新

如何循环更新我的SchoolRegistration表?在学校注册中,id可能有1行或多行但事情是RegModifiedDateTime对于并发目的而言是唯一的,我应该循环以获得该id的正确modifydatetime。

alter procedure [dbo].[del_schoolRegistration]
    @Id bigint, 
    @RegModifiedDateTime datetime
as
begin  
    declare @rowsAffected int
    begin tran 


        --registration
        update SchoolRegistration
                   set Active = 0,
                    ModifiedDateTime = getdate()            
        where (Id = @Id and RegModifiedDateTime = @RegModifiedDateTime or @RegModifiedDateTime is null )


    if (@rowsAffected < 1) begin
        rollback tran
    end
    else begin
        commit tran
    end

    return @rowsAffected

end 

2 个答案:

答案 0 :(得分:1)

   --registration
    ;with tmp as (
        select *, rn=ROW_NUMBER() over (partition by ID order by RegModifiedDateTime desc)
        from SchoolRegistration
        where (Id = @Id and RegModifiedDateTime = @RegModifiedDateTime or @RegModifiedDateTime is null ))
    update tmp
               set Active = 0,
                ModifiedDateTime = getdate()            
    WHERE rn=1

这里发生的事情是,如果你不知道你正在寻找的RegModifiedDateTime(通过将@RegModifiedDateTime传递为NULL),查询将因@RegModifiedDateTime is null而捕获所有ID,但仅更新LATEST RegModifiedDateTime基于row_numbering和CTE表定义。

修改

如果记录不是最新需要更新的记录,则上述查询保留传递直接@RegModifiedDateTime的选项。要始终只更新最新版本,请将WHERE过滤器完全放弃@RegModifiedDateTime

   --registration
    ;with tmp as (
        select *, rn=ROW_NUMBER() over (partition by ID order by RegModifiedDateTime desc)
        from SchoolRegistration
        where Id = @Id)
    update tmp
               set Active = 0,
                ModifiedDateTime = getdate()            
    WHERE rn=1

答案 1 :(得分:-1)

我最终使用光标:

USE AdventureWorks
GO
DECLARE @ProductID INT
DECLARE @getProductID CURSOR
SET @getProductID = CURSOR FOR
SELECT ProductID
FROM Production.Product
OPEN @getProductID
FETCH NEXT
FROM @getProductID INTO @ProductID
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT @ProductID
FETCH NEXT
FROM @getProductID INTO @ProductID
END
CLOSE @getProductID
DEALLOCATE @getProductID
GO