sql server where子句中的用例 我想做的是查询一个日期时间值,这样我就不必在存储过程中这样做了。 if @considerDate =1 begin select * from table where dateCol = @date end else begin select * from table end

sql server where子句中的用例 我想做的是查询一个日期时间值,这样我就不必在存储过程中这样做了。 if @considerDate =1 begin select * from table where dateCol = @date end else begin select * from table end,sql,sql-server,case,Sql,Sql Server,Case,我想做一些像你这样的事情 select * from table where dateCol = ( case when @date is not null then @date ) 在单个查询中如果我正确理解您的意思,这应该可以: SELECT * FROM Table WHERE dateCol = CASE WHEN @date is not null then @d

我想做一些像你这样的事情

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

在单个查询中

如果我正确理解您的意思,这应该可以:

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

您只需要添加
END
关键字

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

如果不想在查询中包含date参数,请将该值设置为null,然后在查询中可以使用null检查来决定是否应用筛选器。

我想问一下ELSE的情况。回答得好。
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)