Search code examples
sqlsql-servercasewhere-clauseclause

SQL Server - Execute first where clause and if valid don't execute second


I have the SQL Server Select statement:

SELECT * 
FROM Table
WHERE(ClientPlants = 621 AND Carriers = 226)
 OR (Carriers = 226 AND ClientPlants IS NULL) 
 ORDER BY ClientPlants

Now problem is when the first is valid, it still executes the second clause after the 'or'. How do I make it so the second clause is only executed if the first clause fails?

As in, if there are no results found for where clause 1 (ClientPlants = 621 AND Carriers = 226), go to 2 (Carriers = 226 AND ClientPlants IS NULL). If there is a result for clause 1, return query and stop.

I tried to look into CASE statement but couldn't see how to add it to my code.

Thanks in advance!


Solution

  • Do you mean something like this:

    IF EXISTS (SELECT * FROM Table WHERE ClientPlants = 621 AND Carriers = 226)
        SELECT * FROM Table WHERE ClientPlants = 621 AND Carriers = 226 ORDER BY ClientPlantsK
    ELSE
        SELECT * FROM Table WHERE Carriers = 226 ORDER BY ClientPlantsK
    ;
    

    Update:

    Given that you are only wanting to return 1 row, I think something like this would work for a single T-SQL query in a stored procedure:

    CREATE PROCEDURE ProcedureName
        @ClientPlants int
        , @Carriers int
    AS
    
    SELECT
        Carriers
        , ClientPlants
        -- Add the rest of the columns
    FROM
        (
            SELECT
                Carriers
                , ClientPlants
                -- Add the rest of the columns
                , ROW_NUMBER() OVER (ORDER BY CASE WHEN ClientPlants = @ClientPlants THEN 0 ELSE 1 END) R
            FROM Table
            WHERE Carriers = @Carriers
        ) Q
    WHERE R = 1
    

    Usage:

    EXEC ProcedureName 621, 226
    

    I've recommended you name your columns rather than using SELECT * to avoid having column R in the output.