触发更新语句后需要很长时间

时间:2016-03-21 15:34:00

标签: sql sql-server sql-server-2008 database-trigger

我创建了一个触发器,如下所示

alter trigger sale_Trigger_Update on sale
after update
as
begin
Declare @old_value  varchar(50)
Declare @new_value varchar(50)
Declare @sale_id UNIQUEIDENTIFIER

DECLARE new_cur CURSOR FORWARD_ONLY READ_ONLY LOCAL FOR
        SELECT saleid
        FROM INSERTED

  open new_cur

          Fetch Next from new_cur into @sale_id
       while @@FETCH_STATUS = 0
        Begin
          set @old_value = (select enddate from deleted where SaleID = @sale_id)
          set @new_value = (select enddate  from inserted where SaleID = @sale_id)
          insert into zzz (old_value,new_value) values(@old_value,@new_value)
        end
         CLOSE new_cur
    DEALLOCATE new_cur

    end

然后我做一个更新声明,如下所示

 update sale
    set enddate = null

Sale表仅包含2

并且执行继续无限制。

我试过

update sale
set enddate = null
where saleid = 10

同样的问题。

然后我强行停止了执行。然后检查sale表和zzz表。没有发生变化。 我确定游标中存在一些问题。有人可以对此有所了解。

**** ****已编辑

实际上我需要检查enddate in deleted is null and enddate in inserted is not null

open new_cur

              Fetch Next from new_cur into @sale_id
           while @@FETCH_STATUS = 0
            Begin
              set @old_value = (select enddate from deleted where SaleID = @sale_id)
              set @new_value = (select enddate  from inserted where SaleID = @sale_id)
            if @old_value = null and @new_value != null
            begin 
               SELECT approval.*,
(select diag.*
from diag diag 
where approval.id =diag.id
FOR XML PATH('diag'), TYPE
),
(select ser.*
from ser ser
where approval.id =ser.id
FOR XML PATH('ser'), TYPE
)
FROM approval approval,
where approval.id = 1
and approval.saleid =@saleid
FOR XML PATH, ELEMENTS,
root('Head')
            end if
            end
             CLOSE new_cur
        DEALLOCATE new_cur

1 个答案:

答案 0 :(得分:0)

关于光标。

你可以用?

替换你的触发器
alter trigger sale_Trigger_Update on sale
after update
as
begin

insert into zzz (old_value,new_value)
select
    --i.SalesID,
    d.enddate,
    i.enddate
from inserted i
inner join deleted d on
    i.SaleID = d.SaleID
where
    d.enddate is null and 
    i.enddate is not null
end