更新触发器获取更新的主键

时间:2013-07-28 11:08:34

标签: sql sql-server

我有一个触发器,但是我需要获取更新记录的主键(比如插入数据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

1 个答案:

答案 0 :(得分:0)

正如Martin所说,您必须了解SQL Server触发器是per语句,而不是每行。因此,在触发器的上下文中,您有两个表 - inserted and deleted,您可以在其中找到有关数据更新的所有信息。如果你真的想要每行处理,你可以使用cursor:

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