2015-05-29 54 views
1

我通過制定一個動態字符串編寫存儲過程:動態字符串 - 作爲執行SQL查詢

下面的查詢是存儲在一個變量的字符串。 我將如何執行此字符串?

DELETE FROM PopularTrends   
WHERE PopularID NOT IN   
(   
SELECT PopularID   
FROM (SELECT *,   
      Row_number()   
      OVER(   
       PARTITION BY COUNTRY,HRefTopic   
       ORDER BY LastModifiedTime desc) AS RN   
    FROM populartrends)A   
    WHERE RN = 1   
) 

回答

1

像這樣:

DECLARE @query NVARCHAR(1000) 
SET @query=N'DELETE FROM PopularTrends   
WHERE PopularID NOT IN   
(   
SELECT PopularID   
FROM (SELECT *,   
      Row_number()   
      OVER(   
       PARTITION BY COUNTRY,HRefTopic   
       ORDER BY LastModifiedTime desc) AS RN   
    FROM populartrends)A   
    WHERE RN = 1   
)' 
EXEC sp_executesql @query 

參考: