触发更新另一个表的特定单元格

时间:2016-07-07 17:52:45

标签: sql-server visual-studio visual-studio-2013 triggers sql-server-2012

我有这两张桌子:

dbo.Restaurants(rid,name,phone,area,address,zip,desc,foodtype,avgRating)

dbo.Reviews(rev_id,rest_id,user_id,taste, service,environment,value,average,comment)

我一直在尝试创建一个执行此操作的触发器: 当dbo.Reviews上的一行被删除,更新或插入时,触发器会计算出餐厅的新平均评级,如下所示:

select rid, round(avg(average)*20,0) as 'average' 
from dbo.Restaurants inner join dbo.Reviews on rid=rest_id 
group by rid

然后在dbo.Restaurants上更新avgRating单元格,其中dbo.Restaurants.rid = dbo.Reviews.rest_id。

到目前为止,我已经想出了这个:

CREATE TRIGGER [defAverage]
ON [dbo].[Reviews]
AFTER UPDATE, DELETE, INSERT
AS
BEGIN

select rid, round(avg(average)*20,0) as 'average' 
from Restaurants inner join Reviews on rid=rest_id 
group by rid
order by 'average' desc
    SET NOCOUNT ON
    UPDATE [dbo].[Restaurants]
    SET [dbo].[Restaurants].avgRating = 'average'
    where [dbo].[Reviews].rest_id = [dbo].[Restaurants].rid

END

这显然不起作用,否则我不会在这里。 我使用的是使用SQL Server Tools 2012的Visual Studio Ultimate 2013.

提前感谢您的时间和建议。

1 个答案:

答案 0 :(得分:2)

有两个名为inserteddeleted的伪表,仅在DML触发器中可用。由于显而易见的原因inserted表格delete为空,deletedinsert的情况下为空,在update的情况下,两个表均为空填充。你可以在触发器中使用它们。

CREATE TRIGGER [defAverage]
ON [dbo].[Reviews]
AFTER UPDATE, DELETE, INSERT
AS
BEGIN

SET NOCOUNT ON
UPDATE [dbo].[Restaurants]
    SET avgRating = round(avg(rv.average)*20,0)
from Restaurants r inner join Reviews rv on r.rid=rv.rest_id 
where r.rid in (select rest_id from inserted
                union
                select rest_id from deleted)
group by r.rid

END