究竟什么触发不起作用

时间:2016-10-01 06:52:41

标签: sql-server

朋友我正在写一个触发器,但有些东西我错过了或者我做错了我不知道。 问题可能是用代码来获取我写的代码存在问题。但我不确定。 当他进入触发器时库存的目的,当你移除碎片时将其添加到你欠债的部分。 添加动作时的方式相同

create trigger StokHareketGirisCikis
on StokHareket
after insert,update,delete
as
declare @stokKodu nvarchar(50),@gc int,@stokId int,@adet int
if exists (select * from deleted)
begin 
    select @stokId=id from deleted  
    select @stokKodu=(select StokKodu from StokKarti where id=@stokId),@adet=Miktar,@gc=GC from deleted
    if @gc=1
    begin
        update StokToplam set borc-=@adet where stokKodu=@stokKodu
        end
        else
        update StokToplam set alacak-=@adet where stokKodu=@stokKodu
end
if exists(select * from inserted)
begin
select @stokId=id from inserted
select @stokKodu=(select StokKodu from StokKarti where id=@stokId),@adet=Miktar,@gc=GC from inserted
    if @gc=1
    begin
        update StokToplam set borc+=@adet where stokKodu=@stokKodu
        end
        else
        update StokToplam set alacak+=@adet where stokKodu=@stokKodu
end

2 个答案:

答案 0 :(得分:1)

主要问题是您使用的是1行(f.e。select @stokId=id from deleted),但inserteddeleted中的行可能更多。您不需要使用变量从此表中获取值,请使用JOIN。

F.e。这部分:

select @stokId=id from deleted  
select @stokKodu=(select StokKodu from StokKarti where id=@stokId),@adet=Miktar,@gc=GC from deleted
if @gc=1
begin
    update StokToplam set borc-=@adet where stokKodu=@stokKodu
    end
    else
    update StokToplam set alacak-=@adet where stokKodu=@stokKodu

可以重写为:

;WITH cte AS (
    select  sk.StokKodu,
            d.Miktar,
            d.GC
    from deleted d
    inner join StokKarti sk
        ON sk.id = d.id
)

update st 
set borc-=c.Miktar
FROM StokToplam st
INNER JOIN cte с
    ON c.stokKodu=st.stokKodu
        AND c.GC = 1

update st 
set alacak-=c.Miktar
FROM StokToplam st
INNER JOIN cte с
    ON c.stokKodu=st.stokKodu
        AND c.GC != 1

答案 1 :(得分:-1)

我照顾好了这个问题。 ' StokId' ' StokKodu'我改成了。工作得很好。

create trigger [dbo].[StokHareketGirisCikis]
on [dbo].[StokHareket]
after insert,update,delete
as
declare @stokKodu nvarchar(50),@gc int,@adet int
if exists (select * from deleted)
begin   
    select @stokKodu=StokKodu,@adet=Miktar,@gc=GC from deleted
    if @gc=1
    begin
        update StokToplam set borc-=@adet where stokKodu=@stokKodu
        end
        else
        update StokToplam set alacak-=@adet where stokKodu=@stokKodu
end
if exists(select * from inserted)
begin
select @stokKodu=StokKodu,@adet=Miktar,@gc=GC from inserted
    if @gc=1
    begin
        update StokToplam set borc+=@adet where stokKodu=@stokKodu
        end
        else
        update StokToplam set alacak+=@adet where stokKodu=@stokKodu
end

@ gofr1非常感谢你