@Age
是否有可能在 where 语句参数中做类似这里发生的事情?
@AGE Varchar(8)
SELECT NAME FROM TABLE WHERE
(
If @AGE='man'
then (AGE = 'man' or AGE = 'boy')
else (AGE = 'man')
)
AND City IS NULL
@Age
是否有可能在 where 语句参数中做类似这里发生的事情?
@AGE Varchar(8)
SELECT NAME FROM TABLE WHERE
(
If @AGE='man'
then (AGE = 'man' or AGE = 'boy')
else (AGE = 'man')
)
AND City IS NULL
是的,像这样:
SELECT NAME FROM TABLE WHERE
((@AGE='man'
AND (AGE = 'man' or AGE = 'boy'))
OR
(@AGE <> 'man'
AND (AGE = 'man')))
AND City IS NULL
请注意,@AGE <> 'man'
可能需要根据 @AGE 变量是否可以为空来调整条件。
我在这里回答了一个非常相似的问题。
这是 WHERE 子句中非常常见的技术。如果您想在 WHERE 子句中应用一些“IF”逻辑,您需要做的就是将带有布尔 AND 的额外条件添加到需要应用它的部分。
一种方法是使用EXEC
并构建字符串命令If's
。
像这样的东西:
declare @t nvarchar(max)
@AGE Varchar(8)
set @t=' SELECT NAME FROM TABLE WHERE '
If @AGE='man' set @t=@t+'(AGE = ''man'' or AGE = ''boy'')'
else set @t=@t+'(AGE = 'man')'
set @t=@t+' AND City IS NULL'
以合取范式(“一系列与”,较少依赖于参数):
SELECT *
FROM TABLE
WHERE ( @AGE <> 'man' OR (AGE IN ('man', 'boy') ) )
AND ( @AGE = 'man' OR AGE = 'man' )
AND CITY IS NULL;
这里的想法是使用隐含重写规则:
( IF x THEN y ) is equivalent to ( NOT ( x ) OR y )
下面是一些测试代码:
WITH T
AS
(
SELECT *
FROM (
VALUES (1, 'man', NULL),
(2, 'boy', NULL),
(3, 'girl', NULL)
) AS T (NAME, AGE, CITY)
),
Params
AS
(
SELECT *
FROM (
VALUES ('man'),
('boy'),
('girl')
) AS T (p_AGE)
),
Results
AS
(
SELECT Params.*, T.*,
CASE WHEN ( ( p_AGE <> 'man' OR (AGE IN ('man', 'boy') ) ) AND ( p_AGE = 'man' OR AGE = 'man' ) ) THEN 'TRUE'
WHEN NOT ( ( p_AGE <> 'man' OR (AGE IN ('man', 'boy') ) ) AND ( p_AGE = 'man' OR AGE = 'man' ) ) THEN 'FALSE'
ELSE 'UNKNOWN'
END AS result_onedaywhen,
CASE WHEN ( AGE='man' OR (p_AGE='MAN' and AGE='boy') ) THEN 'TRUE'
WHEN NOT ( AGE='man' OR (p_AGE='MAN' and AGE='boy') ) THEN 'FALSE'
ELSE 'UNKNOWN'
END AS result_Damien_The_Unbeliever
FROM T, Params
)
SELECT *
FROM Results;
或者你可以使用解码功能