SQL Server Table1 UPDATE Table2

时间:2013-02-12 17:40:47

标签: sql-server-2008

在SQL Server数据库中有两个表。表#1 ClassicsRatingsRatingID为关键,TitleIDRatingComment。表#2,AVGRatingTitleID为关键,AvgRatingCount

以下查询在表#1上最初运行查询时更新表#2:

INSERT INTO AVGRating
   SELECT TitleID, Count(*) AS Count, AVG(Rating) AS AvgRating
   FROM ClassicsRatings
   GROUP BY TitleID
   ORDER BY TitleID

我的问题是:当后续的INSERTS进入表#1时,如何让表#2更新。我尝试了MERGEUPDATE,如下所示:

MERGE AVGRating AS AR
USING ( SELECT TitleID, COUNT(*) AS Count, AVG(Rating) AS AvgRating
FROM ClassicsRatings
GROUP BY RecipeID) AS ClassicsRatings(RecipeID, Count, AvgRating)
ON
(
AR.RecipeID = ClassicsRatings.RecipeID
)
WHEN NOT MATCHED THEN
   INSERT (RecipeID, Count, AvgRating)
   VALUES (ClassicsRatings.RecipeID, ClassicsRatings.Count, ClassicsRatings.AvgRating)
WHEN MATCHED THEN
   UPDATE
    SET AR.Count = ClassicsRatings.Count, 
        AR.AvgARating = ClassicsRatings.AvgRating;

UPDATE AVGRating
SET
AVGRating.TitleID = ClassicsRatings.TitleID,
AVGRating.AvgRating = ClassicsRatings.AvgRating,
AVGRating.Count = ClassicsRatings.Count
FROM AVGRating
INNER JOIN ClassicsRatings ON
AVGRating.TitleID = ClassicsRatings.TitleID
WHERE TitleID = TitleID

我不能做的是插入表1并让表2反映INSERT。任何帮助将不胜感激。

我还使用了以下TRIGGER而没有结果:

CREATE TRIGGER AVGRatingTrigger
ON ClassicsRatings
AFTER INSERT AS
DECLARE @TitleID INT
DECLARE @Count INT
DECLARE @RatingAVG INT
BEGIN
UPDATE AVGRatings
WHERE AVGRatings.TitleID = ClassicsRatings.TitleID 
END

触发器已更改为:

CREATE TRIGGER AVGRatingTrigger
ON ClassicsRatings
AFTER INSERT AS

BEGIN
UPDATE A
SET A.TitleID = I.TitleID,
A.Count = I.Count,
A.AvgRating = I.AvgRating
FROM AVGRating as A
INNER JOIN INSERTED as I ON A.TitelID = I.TitleID 
END

我没有触发器的错误消息,但是,当我将新的评级插入ClassicRatings时,我收到错误消息“Invalid object AvgRating”AVG(等级)AS AvgRating的AvgRating部分似乎在AVGRating表中触发器未识别(初始查询确实识别AvgRating)。我认为这意味着,因为ClassicsRatings实际上没有AvgRating,但会进行计算/聚合并使用计算填充AVGRating表,从而发生冲突。我已经试了两天才能让它发挥作用。我的问题似乎出现在A.Count = I.Count A.AvgRating = I.AvgRating中,因为ClassicsRatings表中的Count实际上是COUNT(*) - 不是ClassicsRatings中的字段而AvgRating实际上是AVG(评级) - 不是ClassicsRatings中的一个字段。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

您需要使用触发器来实现这一目标。 只需创建一个“on insert”触发器,当有第一个表的插入时,它会运行查询。

在触发器中,您应该使用逻辑INSERTED,其中包含插入的行。 类似的东西:

CREATE TRIGGER AVGRatingTrigger
ON ClassicsRatings
AFTER INSERT AS

BEGIN
UPDATE A
SET A.xxx = I.xxx,
    A.yyy = I.yyy,
    ...
FROM AVGRatings as A
INNER JOIN INSERTED as I ON A.TitleID = I.TitleID 
END