I have several different tables, but they all have 2 columns that are the same name. I want to write a stored procedure that searches one column in all of the tables and returns the result. Ideas? I'm fairly nub when it comes to SQL.
views:
30answers:
3
A:
Select myColumn FROM Table1
UNION Select myColumn FROM Table2
UNION Select myColumn FROM Table3
..etc
-- Note all column names have to be the same and have to be in each table for this to work
Eden
2010-06-15 18:28:12
A:
You wouldn't even need a stored procedure...just use a union query.
select field1, field2 from table1 where table1.field1=criteria
union
select field1, field2 from table2 where table2.field1=criteria
union
select field1, field2 from table3 where table3.field1=criteria
etc...
pjabbott
2010-06-15 18:29:18
But your query can be placed in a stored procedure. You shouldn't compare a query with a sproc, queries go inside of the sprocs in which you can add layers of security. So he / she may want to put this into a sproc.
JonH
2010-06-15 18:33:33
+5
A:
The operation you are looking for is UNION
or UNION ALL
.
SELECT * FROM (
SELECT col1, col2 FROM table1
UNION ALL
SELECT col1, col2 FROM table2
UNION ALL
SELECT col1, col2 FROM table3
) all_tables
WHERE all_tables.col1 = 'something'
If you use UNION
rather than UNION ALL
, the database will eliminate duplicate rows that may be in multiple tables. If you know there won't be any duplicates, use UNION ALL
since it is generally much faster.
Eric Petroelje
2010-06-15 18:29:28