简体   繁体   中英

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? As much as posible, I don't want to use dynamic SQL. I've seen this in a similar question but it only selects on 1 table.

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.

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:

If you choose @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)

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. I am assuming you want to use @table to control what the script should do.

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:

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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