在存储过程中执行多个SQL命令

时间:2014-10-08 11:33:31

标签: sql sql-server tsql sql-server-2012

我创建了以下存储过程,该过程应该找到符合某些要求的WebPages表中的所有元素。首先,我(动态地)生成一些SQL查询:

DECLARE @SitesForScan TABLE
(
    command nvarchar(1000)
)

INSERT INTO @SitesForScan(command) 
SELECT ('SELECT TOP ' + convert(varchar(10),[Credits]) + 
        ' * FROM [WebPages] pages WHERE pages.[WebSites_Id] = ' + 
            convert(varchar(10),[Id])) as "commnad"
FROM [WebSites]
WHERE [Credits] > 0

之后,表变量@SiteForScan包含多个SQL命令。现在,我想执行每个命令,合并它们返回的所有结果并返回结果。

我怎样才能做到这一点?

3 个答案:

答案 0 :(得分:0)

您可以使用动态SQL来EXECUTE您的SQL

DECLARE @SQL Nvarchar(MAX)=N'select * from @SitesForScan'

EXEC sp_EXECUTESQL @SQL

答案 1 :(得分:0)

以下语句使用标识列来浏览@SitesForScan表,以便我们可以使用while循环来执行所有查询。

DECLARE @SitesForScan TABLE
(
    id int identity(1,1),
    command nvarchar(1000)
)

INSERT INTO @SitesForScan(command) 
    SELECT ('SELECT TOP ' + convert(varchar(10),[Credits]) + ' * FROM [WebPages] pages WHERE pages.[WebSites_Id] = ' + convert(varchar(10),[Id])) as "commnad"
        FROM [WebSites]
        WHERE [Credits] > 0

declare @i int=1,@sql nvarchar(max)=''
while (@i<=@@ROWCOUNT)
begin
set @sql=(select command from @SitesForScan where id=@i)

EXEC SP_EXECUTESQL @SQL
set @sql=''
set @i=@i+1
end

答案 2 :(得分:0)

通过查看您目前拥有的内容,我认为以下内容会产生您的目标结果(一旦填写空白):

;With Ordered as (
     SELECT wp.*,ROW_NUMBER() OVER (
         PARTITION BY wp.Websites_Id
         ORDER BY --I don't know what column to put here
         ) as rn,
         ws.Credits
     FROM
         WebSites ws
            inner join
         WebPages wp
            on
                ws.Id = wp.Websites_Id
)
SELECT * from Ordered where rn <= Credits

目前,您的查询在中是非确定性的,将检索来自WebSites行(因为您使用TOP而没有ORDER BY)。如果这是整体操作的重要部分,请告诉我。否则,在我的查询中将实际列放在ORDER BY的位置,您应该得到所需的结果。