简体   繁体   English

SQL从任意数量的相同表中选择记录

[英]SQL select records from an arbitrary number of identical tables

I am trying to query a database (SQLServer) with multiple tables of identical structure and with related names ie 我试图查询具有相同结构和相关名称的多个表的数据库(SQLServer),即

[TABLE 01 $TRANSACTIONS]
[TABLE 02 $TRANSACTIONS]
...
[TABLE (n) $TRANSACTIONS]

I have a query returning the desired records on one table at a time and can manually select multiple tables with 我有一个查询,一次一次返回一张表上的所需记录,并且可以手动选择多个表

SELECT {QUERY01} FROM [TABLE 01 $TRANSACTIONS]
UNION
SELECT {QUERY02} FROM [TABLE 02 $TRANSACTIONS]
...
SELECT {QUERY(n)} FROM [TABLE (n) $TRANSACTIONS]

The generic query into which I substitute the required table name is approx 200 lines, involving a ROWNUMBER()/PARTITION BY function, multiple joins to related tables and some ordering. 我替换所需表名的通用查询大约有200行,涉及ROWNUMBER()/ PARTITION BY函数,对相关表的多次连接和某些排序。

Over time, new tables will be added and n will change. 随着时间的流逝,将添加新表,并且n将更改。

Can anyone suggest a way to select the UNION of records from all n tables for arbitrary values of n ? 任何人都可以提出一个方法来从n个任意值的所有n选择表中的记录UNION?

Note: the list of n tables can be easily obtained with a query on the sysobjects table 注意:通过查询sysobjects表可以轻松获得n个表的列表

SELECT Name FROM sysobjects
WHERE Type = 'U'
AND Name LIKE '%$TRANSACTIONS'
ORDER BY Name

AFAIK, your best bet is to use your sysobjects query to generate a new view definition periodically. AFAIK,最好的选择是使用sysobjects查询定期生成新的视图定义。

You might be able to create a DDL trigger which runs the procedure to re-generate this view when your tables change -- I don't really know. 您可能能够创建一个DDL触发器,该触发器将运行该过程以在表更改时重新生成此视图-我真的不知道。 DB designs like this are a trainwreck. 像这样的DB设计是一个沉船。

You could cursor through your sysobjects query and construct the sql statement. 您可以通过sysobjects查询游标并构造sql语句。 Then you can call sp_executesql to run it. 然后,您可以调用sp_executesql来运行它。 From experience, I can tell you that these are a pain in the A$$ to debug. 根据经验,我可以告诉您,这是调试A $$的痛苦。 I would also expect this solution to fall apart with any vendor upgrade. 我还希望该解决方案在任何供应商升级时都会崩溃。 Good luck. 祝好运。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM