SQL 服务器 - 首先执行 where 子句,如果有效则不执行第二个
SQL Server - Execute first where clause and if valid don't execute second
我有 SQL 服务器 Select 语句:
SELECT *
FROM Table
WHERE(ClientPlants = 621 AND Carriers = 226)
OR (Carriers = 226 AND ClientPlants IS NULL)
ORDER BY ClientPlants
现在的问题是当第一个有效时,它仍然执行'or'之后的第二个子句。我该如何做到只有在第一个子句失败时才执行第二个子句?
如,如果没有找到 where 子句 1 (ClientPlants = 621 AND Carriers = 226) 的结果,请转到 2 (Carriers = 226 AND ClientPlants IS NULL)。如果第 1 条有结果,return 查询并停止。
我试图查看 CASE 语句,但看不出如何将它添加到我的代码中。
提前致谢!
你是这个意思吗?
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
你可以使用 CASE WHEN
:
SELECT *
FROM Table
WHERE (CASE WHEN ClientPlants = 621 AND Carriers IN (226) THEN 1
WHEN Carriers IN (226) THEN 1
ELSE 0
END) = 1
ORDER BY ClientPlantsK;
你的意思是这样的吗:
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
;
更新:
鉴于您只想 return 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
。
我有 SQL 服务器 Select 语句:
SELECT *
FROM Table
WHERE(ClientPlants = 621 AND Carriers = 226)
OR (Carriers = 226 AND ClientPlants IS NULL)
ORDER BY ClientPlants
现在的问题是当第一个有效时,它仍然执行'or'之后的第二个子句。我该如何做到只有在第一个子句失败时才执行第二个子句?
如,如果没有找到 where 子句 1 (ClientPlants = 621 AND Carriers = 226) 的结果,请转到 2 (Carriers = 226 AND ClientPlants IS NULL)。如果第 1 条有结果,return 查询并停止。
我试图查看 CASE 语句,但看不出如何将它添加到我的代码中。
提前致谢!
你是这个意思吗?
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
你可以使用 CASE WHEN
:
SELECT *
FROM Table
WHERE (CASE WHEN ClientPlants = 621 AND Carriers IN (226) THEN 1
WHEN Carriers IN (226) THEN 1
ELSE 0
END) = 1
ORDER BY ClientPlantsK;
你的意思是这样的吗:
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
;
更新:
鉴于您只想 return 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
。