如果存在具有这些名称的 table,则执行合并

Perform Union if table with these names exist

我有出勤数据库,每个月都会生成新的 table 像 TRNS0419,TRNS0519,TRNS0619,TRNS0719。为了合并数据,我使用了 Union。 但是每个月我都手动输入 table 名称,如果在生成新 table 这样的 TRNS0819

时自动选择数据,有什么办法吗?

我试过使用 union all 但它没有采用不存在的 table。

Select * from TRNS0419 union all Select * from TRNS0519
union all Select * from TRNS0619 union all Select * from TRNS0719

我的查询没有使用 union all Select * from TRNS0819 因为这在 db

中不可用

它应该合并所有 table 并在 find temp table 中显示结果。 请帮助

在存储过程中包装以下代码:

DECLARE @DynamicTSQLStatement NVARCHAR(MAX);

SELECT @DynamicTSQLStatement = STUFF
(
    (
        SELECT N' UNION ALL SELECT * FROM ' + '[' + SCHEMA_NAME([schema_id]) + '].[' + [name] + ']'
        FROM [sys].[tables]
        WHERE [name] LIKE 'TRNS%'
        FOR XML PATH(''), TYPE
    ).value('.', 'NVARCHAR(MAX)')
    ,1
    ,10
    ,''
);

EXEC sp_executesql @DynamicTSQLStatement;

当从 [sys].[tables] 视图中提取 table 名称时,您可以添加更多过滤器。