T-SQL:从INFORMATION_SCHEMA.TABLES还原的所有表中选择数据

时间:2019-03-27 05:40:11

标签: sql sql-server tsql

我需要从通过以下查询还原的所有表中提取数据:

SELECT TABLE_NAME 
FROM INFORMATION_SCHEMA.TABLES 
WHERE TABLE_NAME LIKE 'ERP_%'

我尝试执行以下查询,但未成功:

SELECT * 
FROM 
    (SELECT TABLE_NAME 
     FROM INFORMATION_SCHEMA.TABLES 
     WHERE TABLE_NAME LIKE 'ERP_%')
WHERE STATUS = 'XXX'

期待您的协助。

2 个答案:

答案 0 :(得分:0)

您可以尝试生成动态SQL语句并执行它:

-- Declarations
DECLARE @stm nvarchar(max)
SET @stm = N''

-- Dynamic SQL
SELECT @stm = (
   SELECT CONCAT(
        N'SELECT * FROM ',
        QUOTENAME(TABLE_NAME),
        N' WHERE [STATUS] = ''XXX''; '
   )
   FROM INFORMATION_SCHEMA.TABLES 
   WHERE TABLE_NAME LIKE 'ERP_%'
   FOR XML PATH('')
)

-- Execution
PRINT @stm
EXEC sp_executesql @stm

答案 1 :(得分:0)

使用动态SQL尝试以下查询:

declare @sql varchar(max) = '';

select @sql = @sql + 'select * from ' + TABLE_NAME + ' where [status] = ''XXX''; '
from INFORMATION_SCHEMA.TABLES
where TABLE_NAME like 'ERP_%';

exec(@sql);