25

我需要有一个这样操作的条件 where 子句:

Select *
From Table
If (@booleanResult)
Begin
  Where Column1 = 'value1'
End
Else
Begin
  Where column1 = 'value1' and column2 = 'value2'
End

任何帮助,将不胜感激。

4

4 回答 4

42

你能做到以下几点吗?

SELECT
    *
FROM
    Table
WHERE
    (@booleanResult = 1
    AND Column1 = 'value1')
OR
    (@booleanResult = 0
    AND Column1 = 'value1'
    AND Column2 = 'value2')
于 2012-05-09T18:10:24.567 回答
14

您可以在WHERE子句中轻松地对条件进行分组:

WHERE
   (@BooleanResult=1 AND Column1 = 'value1')
OR
   (@BooleanResult=0 AND Column1 = 'value1' AND column2 = 'value2')
于 2012-05-09T18:10:59.520 回答
6

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');

位变量设置为 1 (true) 时的脚本:

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

位变量设置为 0 (false) 时的脚本:

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

演示:

单击此处查看 SQL Fiddle 中的演示。

于 2012-05-09T18:27:20.473 回答
1

要提供更简短的答案:

Select *
From Table
Where Column1 = 'value1' and
      coalesce(column2, '') = (case when @BooleanResults = 0 
                                    then 'value1' 
                                    else coalesce( column2, '')
                               end)
于 2012-05-09T18:17:06.893 回答