使用情况在where子句中的SQL Server

问题描述:

什么即时试图做的是做一个查询考虑或不datetime值,所以我不必须这样做在存储过程中使用情况在where子句中的SQL Server

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

我想这样做somethink像

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 
+0

我打算询问有关ELSE的情况。好答案。 – 2013-02-19 00:32:19

你不能做这样的事情这将是更清楚?

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