[英]where condition in Insert/Update Trigger not working
這是我的觸發器:
Create trigger Points
on Posts
after insert, update
As
declare @Id int;
declare @value int;
select @value= Count(i.Message) from Posts i;
select @Id = [PostedBy] from inserted;
update AspNetUsers set User_points = @value * 3
where @Id = @Id
在最后一行,條件總是失敗,它沒有選擇正確的Id並在所有行中的User_Points列中更新相同的值,而不是在特定行中。
我寫了一個插入語句來檢查我返回的值是這樣的:
insert into Employee_Demo(PostedBy, TotalCount)
values (@postedby,@value );
在這里,我在表中得到正確的@postedby值。 以前,我正在嘗試這樣做:
create trigger Points
on Posts
after insert, update
As
declare @value int
declare @postedby int
select @value= Count(Message) from Posts
select @postedby = PostedBy from inserted
update AspNetUsers set User_points = @value * 3
where Id = @postedby
請有人幫我。 如何僅基於ID更新單行。 還有一點,PostedBy不是post表中的主鍵,它是aspnetuser表的外鍵,它包含發布消息的用戶的id值,如下圖所示。
也嘗試了這個:
update AspNetUsers set User_points = @value * 3
FROM INSERTED INNER JOIN Posts ON INSERTED.PostedBy = Posts.PostedBy
INNER JOIN AspNetUsers ON AspNetUsers.Id = inserted.PostedBy
當前,您正在where子句中比較相同的Variable,應該在其中將DB字段與Variable進行比較。
終於讓它與這個查詢一起工作不知道它如何發生
update AspNetUsers set User_points = @value * 3
where Id = (Select PostedBy from inserted)
並刪除@Id或@PostedBy的聲明。 當我聲明這些變量,然后將值從插入的值分配給那些變量,然后在不起作用的地方使用該變量值。 相反,直接從條件起作用的插入表中獲取價值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.