我需要有一个条件where子句,其操作如下:
Select *
From Table
If (@booleanResult)
Begin
Where Column1 = 'value1'
End
Else
Begin
Where column1 = 'value1' and column2 = 'value2'
End
任何帮助将不胜感激。
答案 0 :(得分:33)
你能做到以下几点吗?
SELECT
*
FROM
Table
WHERE
(@booleanResult = 1
AND Column1 = 'value1')
OR
(@booleanResult = 0
AND Column1 = 'value1'
AND Column2 = 'value2')
答案 1 :(得分:12)
您可以在WHERE
子句中轻松对条件进行分组:
WHERE
(@BooleanResult=1 AND Column1 = 'value1')
OR
(@BooleanResult=0 AND Column1 = 'value1' AND column2 = 'value2')
答案 2 :(得分:4)
根据相关脚本,无论变量Column1
是设置为true还是false,您似乎都需要@booleanResult
的条件。所以,我已将该条件添加到WHERE
子句,并在剩余条件中检查变量是否设置为 1 ( true )或是否已设置 0 ( false )然后它还会检查Column2
上的条件。
这只是实现这一目标的另一种方式。
CREATE TABLE MyTable
(
Column1 VARCHAR(20) NOT NULL
, Column2 VARCHAR(20) NOT NULL
);
INSERT INTO MyTable (Column1, Column2) VALUES
('value1', ''),
('', 'value2'),
('value1', 'value2');
DECLARE @booleanResult BIT
SET @booleanResult = 1
SELECT *
FROM MyTable
WHERE Column1 = 'value1'
AND ( @booleanResult = 1
OR (@booleanResult = 0 AND Column2 = 'value2')
);
输出:
COLUMN1 COLUMN2
------- -------
value1
value1 value2
DECLARE @booleanResult BIT
SET @booleanResult = 0
SELECT *
FROM MyTable
WHERE Column1 = 'value1'
AND ( @booleanResult = 1
OR (@booleanResult = 0 AND Column2 = 'value2')
);
输出:
COLUMN1 COLUMN2
------- -------
value1 value2
答案 3 :(得分:1)
提供更短的答案:
Select *
From Table
Where Column1 = 'value1' and
coalesce(column2, '') = (case when @BooleanResults = 0
then 'value1'
else coalesce( column2, '')
end)