开发者

SQL Query for finding a unique Item in one of many tables

开发者 https://www.devze.com 2023-01-20 19:09 出处:网络
I have the need to search for an item that exists in one of many (~20) tables I can safely assume that the item only exists in one of the tables, all tables contains an index with the same column name

I have the need to search for an item that exists in one of many (~20) tables I can safely assume that the item only exists in one of the tables, all tables contains an index with the same column name and value type.

Tables vary in on of their columns, containing one of a few possible value types开发者_StackOverflow (int, string, binary. etc.)

What would be the most efficient way to search for the item, of a few items that match a criteria? Please note that there is NO NEED for any join, as item is uniquely stored in one row in one table.


SQL UNION with the 20+ tables enumerated in the UNION. You could set this up as a view then use the view for selection.

For the single column that varies you could convert all the types to a string for the view.

For an example:

CREATE VIEW Combined_Table AS
SELECT keyfield, Cast(Integerb as varchar) as varcharfield
  FROM table1
UNION
SELECT keyfield, varcharfield
  FROM table2
UNION ...

then you can use the view as a table:

SELECT keyfield, varcharfield
  FROM Combined_table
 WHERE keyfield = 'key'
0

精彩评论

暂无评论...
验证码 换一张
取 消