动态字符串 - 作为sql-query执行

时间:2015-05-29 08:01:13

标签: sql-server-2008

我正在通过构建动态字符串来编写存储过程:

以下查询是存储在变量中的字符串。 我该如何执行这个字符串?

 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 个答案:

答案 0 :(得分: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

参考: