[英]where condition in Insert/Update Trigger not working
This is my trigger: 这是我的触发器:
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
Here, at the last line, where condition always fails.Its not picking correct Id and updating same value in User_Points column in all rows not in particular rows. 在最后一行,条件总是失败,它没有选择正确的Id并在所有行中的User_Points列中更新相同的值,而不是在特定行中。
I have written an insert statement to check what value i get back like this: 我写了一个插入语句来检查我返回的值是这样的:
insert into Employee_Demo(PostedBy, TotalCount)
values (@postedby,@value );
here, i am getting correct @postedby value in table. 在这里,我在表中得到正确的@postedby值。 Previosly, i was trying this:
以前,我正在尝试这样做:
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
please please someone help me. 请有人帮我。 how to update only single row based on Id.
如何仅基于ID更新单行。 One more thing, PostedBy is not the primary key in post table.It is foreign key to aspnetuser table and it contains id value of user who has posted the message as u can see in below image.
还有一点,PostedBy不是post表中的主键,它是aspnetuser表的外键,它包含发布消息的用户的id值,如下图所示。
tried this too: 也尝试了这个:
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进行比较。
Finally got it working with this query dont know how it happens 终于让它与这个查询一起工作不知道它如何发生
update AspNetUsers set User_points = @value * 3
where Id = (Select PostedBy from inserted)
and removing the declaration of @Id or @PostedBy. 并删除@Id或@PostedBy的声明。 when i declared those variable and then assign value from inserted to those variable and then use that variable value in where then it was not working.
当我声明这些变量,然后将值从插入的值分配给那些变量,然后在不起作用的地方使用该变量值。 Instead, directly getting value from inserted table in where condition works.
相反,直接从条件起作用的插入表中获取价值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.