在SQL中将数据从一个表插入另一个表

时间:2013-10-21 10:57:43

标签: sql-server tsql

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

第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步 接下来我想做的是每个项目获取Identity(最后插入的ID),例如:

DECLARE @ID INT= @@IDENTITY

STEP3

我想在STEP 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

我将不胜感激任何帮助

0 个答案:

没有答案