-4

我有一个触发器,但是我需要获取更新记录的主键(比如插入数据 SELECT @Id= @@IDENTITY),因此我可以将它传递给 where 条件。我怎样才能做到这一点?

ALTER TRIGGER [dbo].[CariBakiyeBorcAktar]
       ON  [dbo].[BakimKartiDegisenParcalar]
       AFTER   UPDATE
    AS 
    BEGIN
        -- SET NOCOUNT ON added to prevent extra result sets from
        -- interfering with SELECT statements.
        SET NOCOUNT ON;

    DECLARE @Id int 
    DECLARE @CariId int 
    DECLARE @SId int 
    DECLARE @MId int
    declare @Tutar decimal
    declare @Bakiye decimal
    declare @s decimal = 0


    DECLARE @ParcaId int 


    --how I can I get the last updateed record Identity like this??
    --and pass it to update query as a where condition
    SELECT @Id= @@IDENTITY




    set @SId=(select SId from CariBakiye where Id =@Id)

    select @CariId=tblk.CariId ,@MId=tblk.MId, @SId= tblk.SId,@Tutar=tblk.Tutar from (
    SELECT tbl.CariId , tbl.MId,tbl.SId,tbl.Tutar from (select cb.MId,SUM(bk.Tutar) as  Tutar,bk.SId,cb.Id  as CariId FROM [BakimKartiDegisenParcalar] bk
    join  CariBakiye cb on cb.SId=bk.SId
     where bk.SId  =cb.SId group by bk.SId,cb.MId,cb.Id ) as tbl 
    ) as tblk  where SId = @SId

    set @Bakiye = @s-@Tutar


    update CariBakiye set Borc=@Tutar,Bakiye=@Bakiye where Id=@CariId

    print @Id
        -- Insert statements for trigger here

    END
4

1 回答 1

0

正如 Martin 所说,您必须了解 SQL Server 触发器是按语句而不是按行的。因此,在您的触发器的上下文中,您有两个表 -已插入和已删除,您可以在其中找到有关已更新数据的所有信息。如果你真的想进行每行处理,你可以使用游标:

ALTER TRIGGER [dbo].[CariBakiyeBorcAktar] ON  [dbo].[BakimKartiDegisenParcalar]
AFTER UPDATE
AS 
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    DECLARE @Id int 
    DECLARE @CariId int 
    DECLARE @SId int 
    DECLARE @MId int
    declare @Tutar decimal
    declare @Bakiye decimal
    declare @s decimal = 0

    DECLARE @ParcaId int 


    declare tr_cursor cursor local fast_forward for
        select ID from inserted

    while 1 = 1
    begin
        fetch tr_cursor into @Id
        if @@fetch_status <> 0 break

        set @SId=(select SId from CariBakiye where Id =@Id)

        select @CariId=tblk.CariId ,@MId=tblk.MId, @SId= tblk.SId,@Tutar=tblk.Tutar from (
        SELECT tbl.CariId , tbl.MId,tbl.SId,tbl.Tutar from (select cb.MId,SUM(bk.Tutar) as  Tutar,bk.SId,cb.Id  as CariId FROM [BakimKartiDegisenParcalar] bk
        join  CariBakiye cb on cb.SId=bk.SId
         where bk.SId  =cb.SId group by bk.SId,cb.MId,cb.Id ) as tbl 
        ) as tblk  where SId = @SId

        set @Bakiye = @s-@Tutar


        update CariBakiye set Borc=@Tutar,Bakiye=@Bakiye where Id=@CariId

        print @Id
            -- Insert statements for trigger here
    end
    close tr_cursor
    deallocate tr_cursor
END
于 2013-07-28T11:25:51.337 回答