tags:

views:

48

answers:

1

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 (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.

Amit

+3  A: 

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'
Paul Morgan
(probably a newbie question) Can you maybe explain/demonstrate using a view? (first time crossing this term). 10x
Amit Ben Shahar
Another concern is performance, so i would like to stop the search once a result is found (as i know there is only 1), so would applying a ROWCOUNT (max results) make sure that the query stops after one result?
Amit Ben Shahar
Or better phrased: Another concern is performance, so i would like to stop the search once a result is found (as i know there is only 1), so how do i apply a limit in a way that ensures the query stops after one result?
Amit Ben Shahar
If, as you say, there is only one row for each key then you don't need to do any limits. Just make sure you have an index of the key on each table. Then when you select on the view it would just have to check each table's index once.
Paul Morgan
@Paul: The point was avoiding checking additional indexes when for instance the result is found in the first table, then checking the others is redundant..
Amit Ben Shahar