临时表查询作为表返回

时间:2019-01-28 07:22:34

标签: sql sql-server tsql

我有一个表(ReportTest),其中有其他表(Defectpareto)列。我正在尝试使用ReportTest表访问Defectpareto表列。但是我做不到。 我试图编写一个存储过程和查询,两者都将字符串作为输出返回给我

ReportTest table:
ID_column Reportname    Tablename       Column1     Column2     Column3
1         Defect_Pareto Defectpareto    ID_Column   Defectname  Defectcount

Defectpareto table:
ID_column   Defectname  Defectcount
1           Breakdown   15
2           Temperature 300

查询:

`SeLECT COALESCE (CHAR(13), '') + 'Select Column2, Column3 FROM '+ Tablename + ' Where ID_Column = 1' FROM ReportTest`

存储过程:

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER  PROCEDURE [dbo].[StgTable]
AS

BEGIN
DECLARE @Tables VARCHAR(8000) 
SeLECT @Tables = COALESCE(@Tables + CHAR(13), '') + 'SELECT Column2, Column3 FROM '+ Tablename + ' Where ID_Column = 1'
FROM ReportTest
select @Tables
end

如何进行此操作以获取表格的输出

1 个答案:

答案 0 :(得分:0)

一旦您将列和表名放在字符串上,您只需要使用 exec 动态调用该SQL字符串。

更改:

declare @DynSQL varchar(1000) 
set @DynSQL = 'select ......'

select @DynSQL 

与:

declare @DynSQL varchar(1000);

select @DynSQL = ' SELECT ' + Column2' + ', ' + Column3 + 
                 ' FROM '+ Tablename
from ReportTest
where ID_Column = 1;

exec (@DynTable);

您的标签都适用于mySql和SQL Server。我给您的答案是针对SQL Server的,这就是您的代码对我而言的样子。