将查询结果存储到varible - SQL中

时间:2018-06-12 11:38:33

标签: sql-server sql-server-2008

有问题

my_table

我有一张桌子" my_table"如图所示。 我创建了一个名为" variable_1"的变量。我在其中运行查询:

DECLARE @variable_1 nvarchar(4000) = 'SELECT Header FROM my_table WHERE rule = ''rule_1'''

执行此操作时,exec(@variable_1)

我得到结果:

标题

  • OP1
  • OP3

我想将 variable_1 的结果存储到一个新变量" Variable_2" 。 我可以这样做吗?

DECLARE @variable_2 nvarchar(4000) = exec(variable_1)

最终我想将variable_1的结果(将是op1,op3)存储到variable_2中并打印一个命令,如" SELECT op1,op3 from ..."

SELECT(来自variable_1的结果)....

DECLARE @sql nvarchar(4000)

SET @sql = 'SELECT ' + @variable_2

所以当我打印@sql时,我得到的结果是: SELECT op1,op3

谢谢!

1 个答案:

答案 0 :(得分:0)

试试这个

IF OBJECT_ID('Tempdb..#Table')IS NOT NULL
DROP TABLE #Table
CREATE TABLE #Table (Header varchar(10),[Order] INT,Rules   varchar(10))
INSERT INTO #Table
SELECT 'op1',1,'rule_1' UNION ALL
SELECT 'op2',2,'rule_2' UNION ALL
SELECT 'op3',3,'rule-3' 

SELECT * FROM #Table

DECLARE @variable_1 NVARCHAR(4000) = 'SELECT STUFF((SELECT '', '' + Header FROM #Table  WHERE Rules IN( ''rule_1'',''rule_2'') FOR XML PATH ('''')),1,1,'''')'


DECLARE @Temp TABLE (variable_2 nvarchar(4000))
INSERT INTO @Temp
EXEC (@variable_1)

DECLARE @sql nvarchar(4000)

SET @sql = (SELECT 'SELECT ' + variable_2 +' From' FROM @Temp)
SELECT @sql AS ExpectedResult
--PRINT @sql

结果

ExpectedResult
--------------
SELECT  op1, op2