执行Select Statement的结果,而Select语句又是select

时间:2018-06-05 22:05:53

标签: sql-server

我创建了一个包含10个Select查询的表。我想从该表中获得3个随机查询并执行所有这3个查询以获得结果。我尝试使用EXEC,但它没有用。我不想使用游标,因为我想在一个批处理中执行3个查询的结果。我使用的查询是

DECLARE @SqlStmt nvarchar(MAX)

SET @SqlStmt = 'SELECT TOP (3) SQLQuery FROM [dbo].[Load_Test_Queries] ORDER BY NEWID()'

EXEC (@SqlStmt)

我得到的结果是

SQLQuery

--------------------------------

SELECT TOP 10000 * FROM [dbo].[vw_UI_3PP] WHERE ID IN (80079217,80079218,80079219,80079220,80079222,80079229,80079274,80080221,80080223,80080818,80080852,80080918,80080969,80081051,80081354,80081587,80081617,80081716) OR Range > '70-80%'

SELECT TOP 2500 * FROM [dbo].[vw_UI_3PP] Where Code BETWEEN 1010 AND 1300

SELECT TOP 5 * FROM [dbo].[vw_UI_3PP]

我需要的是一批中所有这三个陈述的结果。想象一下,复制这个结果并一次性在另一个会话中执行。

1 个答案:

答案 0 :(得分:0)

我想您遗失的是如何将SELECT TOP 3查询的结果作为单个nvarchar字符串,以便您可以EXEC

drop table #tmp;
select * into #tmp from (
  select 'select 1' as SQLQuery union all
  select 'select 2' union all
  select 'select 3'
)x;

DECLARE @SqlStmt nvarchar(MAX)
SELECT @SqlStmt = coalesce(@SqlStmt, '') + SQLQuery from (
   SELECT TOP (3) SQLQuery FROM #tmp) x
--print @SqlStmt
EXEC (@SqlStmt)