2013-02-19 48 views
3

什麼即時試圖做的是做一個查詢考慮或不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 
      ) 

在一個單一的查詢

回答

4

如果我正確理解你,這應該工作:

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

你只需要添加END關鍵字

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

我打算詢問有關ELSE的情況。好答案。 – 2013-02-19 00:32:19

2

你不能做這樣的事情這將是更清楚?

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