简体   繁体   English

SQL Server:从tableA或tableB OR Both中选择

[英]SQL Server : select from tableA OR tableB OR Both

Is there a way to select from table A , table B or both tables in SQL Server? 有没有办法从SQL Server中的table Atable B或两个表中进行选择? As much as posible, I don't want to use dynamic SQL. 尽可能多,我不想使用动态SQL。 I've seen this in a similar question but it only selects on 1 table. 我在一个类似的问题中看过这个,但它只在1个桌子上选择。

Declare @table = 1

SELECT *
FROM Table1
WHERE <stuff>
AND @Table = 1

UNION ALL

SELECT *
FROM Table2
WHERE <stuff>
AND @Table = 2

You can try this: 你可以试试这个:

You have two solution about value @table. 你有两个关于价值@table的解决方案。

You can consider @table = NULL about selection of both tables, or you can consider @table = value (for example 3 as sum of 1 and 2), so your query becomes: 您可以考虑@table = NULL关于两个表的选择,或者您可以考虑@table = value(例如3作为1和2的总和),因此您的查询变为:

If you choose @table = NULL: 如果选择@table = NULL:

Declare @table = NULL

SELECT *
FROM Table1
WHERE <stuff>
AND (@Table = 1 OR @table IS NULL)

UNION ALL

SELECT *
FROM Table2
WHERE <stuff>
AND (@Table = 2 OR @table IS NULL)

If you choose @Table = value (for example 3) 如果选择@Table = value(例如3)

Declare @table = 3

SELECT *
FROM Table1
WHERE <stuff>
AND (@Table = 1 OR @table = 3)

UNION ALL

SELECT *
FROM Table2
WHERE <stuff>
AND (@Table = 2 OR @table = 3)

You can use the IF...ELSE statements to achieve this as shown below. 您可以使用IF ... ELSE语句来实现此目的,如下所示。 I am assuming you want to use @table to control what the script should do. 我假设你想使用@table来控制脚本应该做什么。

Declare @table = 1

IF @table = 1 
BEGIN
    SELECT *
    FROM Table1  
    WHERE <stuff>
END

ELSE IF @table = 2
BEGIN
    SELECT *
    FROM Table2
    WHERE <stuff>
END

ELSE IF @table = 3 /* OR @table IN (1,2) --depends on how you want to handle this*/
BEGIN
    SELECT *
    FROM Table1
    WHERE <stuff>

    UNION ALL

    SELECT *
    FROM Table2
    WHERE <stuff>
END

The script will stop as soon as the condition is satisfied. 一旦条件满足,脚本将立即停止。 For example IF @Table = 2, only the following sections of script will run: 例如,IF @Table = 2,只运行以下脚本部分:

ELSE IF @table = 2
BEGIN
    SELECT *
    FROM Table2
    WHERE <stuff>
END

Hope this helps: 希望这可以帮助:

SELECT maker, Product.model AS model_1, PC.model AS model_2, price
FROM Product INNER JOIN PC ON PC.model = Product.model
ORDER BY maker, PC.model;

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

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