在另一个查询中执行动态查询

时间:2014-08-01 16:05:10

标签: sql sql-server

我有一张看起来像这样的表

sql_stmt                             table
---------                            ------
'select max(date) from table1'       table1
'select max(date) from table2'       table2
'select max(date) from table3'       table3

如何查询此表,以便最终返回以下结果。基本上我想在列中执行语句并按原样返回其他列。

max_date               table
-------                -------
2014-07-01             table1
2012-12-31             table2
2014-01-01             table3

1 个答案:

答案 0 :(得分:3)

table列是不必要的,因为您的sql_stmt列已经定义了查询将针对哪个表执行。你可以这样做:

USE tempdb;

/*  first we create some test tables and data */

CREATE TABLE dbo.Statements
(
    sql_stmt NVARCHAR(255)
);

INSERT INTO dbo.Statements VALUES 
    ('select max(somedate), ''table1'' from table1')
    ,('select max(somedate), ''table2'' from table2')
    ,('select max(somedate), ''table3'' from table3');

CREATE TABLE dbo.table1
(
    SomeDate DATETIME DEFAULT (GETDATE())
)

INSERT INTO dbo.table1 VALUES (DEFAULT);
GO 100 /* insert 100 rows */

CREATE TABLE dbo.table2
(
    SomeDate DATETIME DEFAULT (GETDATE())
)

INSERT INTO dbo.table2 VALUES (DEFAULT);
GO 100 /* insert 100 rows */

CREATE TABLE dbo.table3
(
    SomeDate DATETIME DEFAULT (GETDATE())
)

INSERT INTO dbo.table3 VALUES (DEFAULT);
GO 100 /* insert 100 rows */


/* Now to actually run the sql_stmt statements  */

DECLARE @sql NVARCHAR(max);  /* MUST be a VARCHAR(MAX) for sp_executesql */


/* CASE WHEN and COALESCE are used to prevent 'UNION ALL' being placed at
    the start of the @sql string */
SELECT @sql = CASE WHEN COALESCE(@sql,'') = '' THEN '' ELSE @sql + ' UNION ALL ' END
             + sql_stmt 
FROM dbo.Statements;

SELECT @sql;  /* This allows you to see the intermediate result
                 of concatenating the sql statements */


/*  run the generated @sql statement */
EXEC sp_executesql @sql;

返回:

enter image description here