sql server where 子句中的用例

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14947796/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 13:44:30  来源:igfitidea点击:

use case in where clause sql server

sqlsql-servercase

提问by user2085104

what im trying to do is to make a query consider or not a datetime value so i dont have to do this in a stored procedure

我想做的是让查询考虑或不考虑日期时间值,所以我不必在存储过程中执行此操作

if @considerDate =1
    begin
        select * from table 
        where dateCol = @date
    end
else
    begin 
        select * from table
    end

i would like to do somethink like

我想做点什么

select * from table
where   dateCol = ( case 
                    when  @date is not null
                    then @date
            )

In an single query

在单个查询中

回答by John Woo

you just need to add ENDkeyword

你只需要添加END关键字

SELECT * 
FROM    tableName
WHERE   dateCol =   CASE WHEN @considerDate =1
                         THEN @date 
                         ELSE dateCol 
                    END

回答by sgeddes

If I'm understanding you correctly, this should work:

如果我正确理解你,这应该有效:

SELECT * 
FROM Table
WHERE dateCol = 
   CASE WHEN @date is not null then @date ELSE dateCol END

回答by mattyc

if @considerDate =0
    begin
        -- set the variable to null so the select will return all rows from table
        set @date = null
    end

SELECT *
FROM table
WHERE dateCol = IsNull(@date, dateCol)

If you don't want to include the date parameter in your query, set the value to null and in your query you can use a null check to decide if it will apply the filter.

如果您不想在查询中包含日期参数,请将值设置为 null,并且在您的查询中,您可以使用 null 检查来决定它是否会应用过滤器。