SQL Server - 执行第一个where子句,如果有效则不执行第二个

时间:2017-11-22 20:37:18

标签: sql sql-server case where clause

我有SQL Server Select语句:

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

现在问题是,当第一个有效时,它仍然会在'或'之后执行第二个子句。如何使第二个子句仅在第一个子句失败时执行?

如果没有找到where子句1(ClientPlants = 621 AND Carriers = 226)的结果,请转到2(Carriers = 226 AND ClientPlants IS NULL)。如果第1条有结果,则返回查询并停止。

我试着查看CASE语句,但看不到如何将其添加到我的代码中。

提前致谢!

3 个答案:

答案 0 :(得分:1)

您可以使用-D DEBUG

CASE WHEN

答案 1 :(得分:1)

你的意思是这样的:

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
;

<强>更新

鉴于您只想返回1行,我认为这样的东西适用于存储过程中的单个T-SQL查询:

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

用法:

EXEC ProcedureName 621, 226

我建议您为列命名,而不是使用SELECT *来避免在输出中包含列R

答案 2 :(得分:0)

你的意思是这样吗?

SELECT a.*
       CASE WHEN ClientPlants = 621 AND Carriers = 226 THEN column
            WHEN ClientPlans <> 621 AND Carriers = 226 THEN column
         ELSE NULL
        END Column

 FROM table A