[英]Combine results of multiple queries as one result in a SQL Server stored procedure
[英]query multiple tables and combine results into one return table for stored procedure?
我有几个不同的表,但它们都有2个相同名称的列。 我想编写一个存储过程,该过程搜索所有表中的一列并返回结果。 有想法吗? 在SQL方面,我还算不上什么。
您要查找的操作是UNION
或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'
如果使用UNION
而不是UNION ALL
,数据库将消除可能在多个表中重复的行。 如果您知道不会有任何重复,请使用UNION ALL
因为它通常要快得多。
Select myColumn FROM Table1
UNION Select myColumn FROM Table2
UNION Select myColumn FROM Table3
..等等
-注意所有列名必须相同并且必须在每个表中才能正常工作
您甚至不需要存储过程...只需使用联合查询即可。
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...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.