没有游标重写这个?

时间:2011-02-01 20:02:43

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

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

reg_Id and ModifiedDateTime并根据此更新。

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

reg_id         id     active        modifydatetime 
-------------------------------------------------- 
432           564       1              2008-12-14 13:15:38.750         
234           564       1              2009-12-14 14:15:50.470         
432           564       1              2007-12-14 14:19:46.703

这是一个性能噩梦,我知道,我需要帮助重写这个sp wihout游标,可能吗?

alter procedure [dbo].[Delete_Student]
    @StudentId bigint, 
    @ModifiedById bigint,
    @ModifiedDateTime datetime 
as
begin   
    begin tran 

            update  Student
            set Active = 1, 
                ModifiedById = @ModifiedById, 
                ModifiedDateTime = getdate() 
            where StudentId = @StudentId and 
                  ModifiedDateTime = @ModifiedDateTime or @ModifiedDateTime is null         

            --Registration       
            Declare @RegStudentId bigint
            DECLARE @RegistrationId bigint
            declare @RegModifiedDateTime datetime
            DECLARE CursorReg CURSOR READ_ONLY  
            FOR
                SELECT StudentId, ModifiedDateTime, RegistrationId 
                FROM Registration where StudentId = @StudentId

            OPEN CursorReg
            FETCH NEXT FROM CursorReg
            INTO @RegStudentId,@RegModifiedDateTime,@RegistrationId

            WHILE @@FETCH_STATUS = 0
            BEGIN
                update Registration
                set Active = 0,        
                ModifiedById = @ModifiedById,
                ModifiedDateTime = getdate() 
                where RegistrationId = @RegistrationId and 
                      ModifiedDateTime = @RegModifiedDateTime or @RegModifiedDateTime is null

                FETCH NEXT FROM CursorReg
                INTO @RegStudentId,@RegModifiedDateTime,@RegistrationId
            END
            CLOSE CursorReg
            DEALLOCATE CursorReg

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

    return @@rowcount

end 

1 个答案:

答案 0 :(得分:1)

对于类似注册声明的内容,您似乎可以使用

update Registration
   set Active = 0,
       ModifiedById = @ModifiedById,
       ModifiedDateTime = getdate()
    where StudentId = @StudentId

所有循环似乎都没有添加任何东西,因为没有分支逻辑或任何困难的东西。我没有花太多时间来分析sql,但是如果这不起作用那么就告诉我们原因。

快速查看其他陈述让我觉得你可以对所有陈述做同样的事情。

请注意,对于每次更新,您的ModifiedDateTime都会有所不同,因此您可能希望在存储过程的开头提取它,并为每次更新使用相同的DateTime。