如何创建条件WHERE子句?

时间:2012-05-09 18:07:13

标签: sql sql-server-2005 where-clause

我需要有一个条件where子句,其操作如下:

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

任何帮助将不胜感激。

4 个答案:

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

当位变量设置为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

演示:

Click here to view the demo in SQL Fiddle.

答案 3 :(得分:1)

提供更短的答案:

Select *
From Table
Where Column1 = 'value1' and
      coalesce(column2, '') = (case when @BooleanResults = 0 
                                    then 'value1' 
                                    else coalesce( column2, '')
                               end)