0

我需要执行以下操作来计算客户评论并将其显示在页面上:

STEP 1. 从 T1 中选择数据,统计记录并计算评分

SELECT COUNT(Rating) As ReviewCount, 
       ObjectID as ObID, 
       SUM(Rating)/COUNT(Rating) As ReviewScore
FROM [dbo].[Comment]
WHERE ObjectTypeID ='2' AND StatusID ='2'
GROUP BY ObjectID

这段代码工作正常。

接下来我想做的是将计算出的 ReviewScore 值插入 T2

INSERT INTO [dbo].[AttributeValue] (AttributeID, Value, SortOrder)
           VALUES (5,ReviewScore, 29)

第 2 步接下来我要做的是为每个项目获取身份(最后插入的 ID),例如:

DECLARE @ID INT= @@IDENTITY

第三步

我想在步骤 2 中获取每个插入行的 @@Identity 并插入新数据:

------- AtribbuteID is always 5
---- ObID  is taken from the STEP 1

INSERT INTO [dbo].[AttributeObjectValue]  
        ([AttributeID],[ObjectID],[Value],[AttributeValueID])
         VALUES (5,ObID,ReviewScore,@ID)

我正在尝试使用 CTE 表,但无法正常工作:

BEGIN  TRAN

GO

;WITH CTE (ReviewCount, ObjectID, ReviewScore)

AS

(

SELECT COUNT(Rating) As ReviewCount, 
        ObjectID as ObID, 
        SUM(Rating)/COUNT(Rating) As ReviewScore
FROM [dbo].[Comment]
WHERE ObjectTypeID ='2' AND StatusID ='2'
GROUP BY ObjectID
)

INSERT INTO [dbo].[AttributeValue] (AttributeID, Value, SortOrder)
        VALUES (5,ReviewScore, 29)

SELECT ReviewCount FROM CTE

DECLARE @ID INT= @@IDENTITY

INSERT INTO [dbo].[AttributeObjectValue]  
      ([AttributeID],[ObjectID],[Value],[AttributeValueID])
       VALUES (5,ObID,ReviewCount,@ID)


GO

ROLLBACK TRAN

我将不胜感激

4

0 回答 0