我需要有一个这样操作的条件 where 子句:
Select *
From Table
If (@booleanResult)
Begin
Where Column1 = 'value1'
End
Else
Begin
Where column1 = 'value1' and column2 = 'value2'
End
任何帮助,将不胜感激。
我需要有一个这样操作的条件 where 子句:
Select *
From Table
If (@booleanResult)
Begin
Where Column1 = 'value1'
End
Else
Begin
Where column1 = 'value1' and column2 = 'value2'
End
任何帮助,将不胜感激。
你能做到以下几点吗?
SELECT
*
FROM
Table
WHERE
(@booleanResult = 1
AND Column1 = 'value1')
OR
(@booleanResult = 0
AND Column1 = 'value1'
AND Column2 = 'value2')
您可以在WHERE
子句中轻松地对条件进行分组:
WHERE
(@BooleanResult=1 AND Column1 = 'value1')
OR
(@BooleanResult=0 AND Column1 = 'value1' AND column2 = 'value2')
Column1
根据有问题的脚本,无论变量@booleanResult
设置为真还是假,您似乎都需要条件。因此,我已将该条件添加到WHERE
子句中,并在其余条件中检查变量是否设置为1 ( true ) 或者是否设置为0 ( false ),然后它还将检查条件 on 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
要提供更简短的答案:
Select *
From Table
Where Column1 = 'value1' and
coalesce(column2, '') = (case when @BooleanResults = 0
then 'value1'
else coalesce( column2, '')
end)