将两个单独查询的内容合并为一个并进行更新

时间:2012-01-14 13:15:00

标签: sql sql-server-2005

希望我正确地描述这一点。我有以下两个单独正常工作的SQL更新查询。我需要在第一个字段中更新字段,并在第二个SQL的一部分中使用它。

这是第一个。

UPDATE Products_Joined SET TechSpecs = 'var srating_' 
+ Products_Joined.ProductCode + '="' + CAST(Reviews.AverageRating AS VARCHAR) + '";var rcount_' + Products_Joined.ProductCode + '="' + CAST(Reviews.TotalRatings AS VARCHAR) + '";' 

FROM Products_Joined LEFT OUTER JOIN (
SELECT Reviews.ProductCode, AVG(Reviews.Rate) AS AverageRating, COUNT(Reviews.ReviewID) AS TotalRatings
FROM Reviews
GROUP BY Reviews.ProductCode
) AS Reviews ON Products_Joined.ProductCode = Reviews.ProductCode;

这是第二个。

DECLARE @OpenTag varchar(100)
SET @OpenTag = '<script type="text/javascript" language="javascript">'

UPDATE Products_Joined
SET TechSpecs  = STUFF(CAST(TechSpecs AS VARCHAR(MAX)) ,
                   CHARINDEX(@OpenTag, CAST(TechSpecs AS VARCHAR(MAX)) ,1)  + LEN(@OpenTag),
                        CHARINDEX('</script>',CAST(TechSpecs AS VARCHAR(MAX)) ,1)-(CHARINDEX(@OpenTag, CAST(TechSpecs AS VARCHAR(MAX)) ,1)  + LEN(@OpenTag)), 
                   '*****HERE IS WHERE I WANT TO PUT THE FIELD FROM THE FIRST SQL QUERY*******')
WHERE TechSpecs LIKE '%<script type="text/javascript" language="javascript">%</script>' 

1 个答案:

答案 0 :(得分:1)

您可以利用SQL Server的OUTPUT子句(从SQL Server 2005开始)将第一个查询的结果输出到变量中,您可以在第二个查询中使用该变量。