2016-04-08 50 views
2

我試圖將此CASE語句設置爲一個變量,但我得到的列中重複的日期相同。這個特殊的CASE聲明正在調整夏令時。我在其他查詢中使用它,但希望縮短這些查詢的範圍,只將它作爲變量的頂部。SQL CASE變量

DECLARE @newdate as Datetime 

SELECT @newdate = 
CASE WHEN 
(a.REQDATE BETWEEN '2014-11-02' AND '2015-03-08' 
OR a.REQDATE BETWEEN '2015-11-01' AND '2016-03-13' 
OR a.REQDATE BETWEEN '2016-11-06' AND '2017-03-12' 
OR a.REQDATE BETWEEN '2017-11-05' AND '2018-03-11' 
OR a.REQDATE BETWEEN '2018-11-04' AND '2019-03-10') 
THEN  CONVERT(datetime,SWITCHOFFSET(CONVERT(datetimeoffset,a.REQDATE),'-08:00')) 
ELSE  CONVERT(datetime,SWITCHOFFSET(CONVERT(datetimeoffset,a.REQDATE),'-07:00')) 
END 

FROM TABLE a inner join TABLE b on a.REQDATE = b.REQDATE 


SELECT 
@newdate, b.REQDATE --control column 
FROM TABLE b 

結果:

(No column name)  | REQDATE 
2016-04-08 13:00:52.000 | 2015-11-02 15:41:25.000 
2016-04-08 13:00:52.000 | 2016-02-02 10:25:54.000 
2016-04-08 13:00:52.000 | 2016-02-11 12:59:10.000 

讓我補充一些更多的信息了這一點。我想替換下面的代碼:

SELECT 
CASE WHEN (b.REQDATE BETWEEN '2014-11-02' AND '2015-03-08' 
OR b.REQDATE BETWEEN '2015-11-01' AND '2016-03-13' 
OR b.REQDATE BETWEEN '2016-11-06' AND '2017-03-12' 
OR b.REQDATE BETWEEN '2017-11-05' AND '2018-03-11' 
OR b.REQDATE BETWEEN '2018-11-04' AND '2019-03-10') 
THEN  CONVERT(datetime,SWITCHOFFSET(CONVERT(datetimeoffset,b.REQDATE),'-08:00')) 
ELSE CONVERT(datetime,SWITCHOFFSET(CONVERT(datetimeoffset,b.REQDATE),'-07:00')) END   AS "DateOpened" 
FROM TABLE 

有了這個:

SELECT 
@newdate 
FROM TABLE 

基本上創建變量了CASE語句

+0

目前還不清楚你問什麼。你的問題具體是什麼? – dave

+1

'@ newdate'是一個單值變量。它不能保存多個值。 –

回答

0

相反@newDate可變的,聲明一個臨時表,並插入記錄到那。完成後,只需將表格數據與表格b或任何其他需要關聯並獲得結果的表格結合起來。

3

一個變量只能保存一個值。什麼,你需要做的是移動這種情況下,語句轉換成一個功能...

CREATE FUNCTION dbo.DST(@d datetime) 
RETURNS datetime 
AS 
BEGIN 
    RETURN CASE WHEN 
    (@d BETWEEN '2014-11-02' AND '2015-03-08' 
    OR @d BETWEEN '2015-11-01' AND '2016-03-13' 
    OR @d BETWEEN '2016-11-06' AND '2017-03-12' 
    OR @d BETWEEN '2017-11-05' AND '2018-03-11' 
    OR @d BETWEEN '2018-11-04' AND '2019-03-10') 
    THEN  CONVERT(datetime,SWITCHOFFSET(CONVERT(datetimeoffset,@d),'-08:00')) 
    ELSE  CONVERT(datetime,SWITCHOFFSET(CONVERT(datetimeoffset,@d),'-07:00')) 
    END 
END 
GO 

SqlFiddle