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

Perform Union if table with these names exist(如果存在具有这些名称的表,则执行联合)
本文介绍了如果存在具有这些名称的表,则执行联合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我有考勤数据库,每个月都会生成新表像 TRNS0419,TRNS0519,TRNS0619,TRNS0719.为了合并数据,我使用了 Union.但是每个月我都手动输入表名,有没有办法在生成新表时自动选择数据,例如 TRNS0819

I have attendance database where every month new table get generated like TRNS0419,TRNS0519,TRNS0619,TRNS0719.To combine data i have used Union. But every month i have enter table name manually, Is there any way if automaticalls picks data when ever new table gets generated such TRNS0819

我尝试过使用 union all,但它没有使用不存在的表.

I have tried using union all but its isnt taking table which is not present.

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

我的查询没有采用 union all Select * from TRNS0819 因为这在 db 中不可用

my query is not taking union all Select * from TRNS0819 because this isn't available in db

它应该组合所有表并在查找临时表中显示结果.请帮忙

It should combine all tables and show result in find temp table. Please help

推荐答案

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

Wrap the following code in stored procedure:

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] 视图中提取表名时,您可以添加更多过滤器.

You can add more filters when table name is extracted from the [sys].[tables] view.

这篇关于如果存在具有这些名称的表,则执行联合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

ibtmp1是非压缩的innodb临时表的独立表空间,通过innodb_temp_data_file_path参数指定文件的路径,文件名和大小,默认配置为ibtmp1:12M:autoextend,也就是说在文件系统磁盘足够的情况下,这个文件大小是可以无限增长的。 为了避免ibtmp1文件无止境的暴涨导致
SQL query to group by day(按天分组的 SQL 查询)
What does SQL clause quot;GROUP BY 1quot; mean?(SQL 子句“GROUP BY 1是什么意思?意思是?)
MySQL groupwise MAX() returns unexpected results(MySQL groupwise MAX() 返回意外结果)
MySQL SELECT most frequent by group(MySQL SELECT 按组最频繁)
Include missing months in Group By query(在 Group By 查询中包含缺失的月份)