這是一個簡單的方法來做到這一點。工程就好了
SELECT CASE WHEN SUBSTRING(CAST(CAST(Date AS DATE) AS NVARCHAR),6,10)<SUBSTRING(CAST(CAST(GETDATE() AS DATE) AS NVARCHAR),6,10)
THEN datefromparts(2017, month(Date), day(Date))
ELSE datefromparts(2016, month(Date), day(Date)) END
FROM datetable
WHERE categoryid = 3;
讓我知道它是否也適用於你。
櫃面您正在運行SQL Server 2008,DATEFROMPARTS
將無法正常工作,而不是使用
SELECT CASE WHEN SUBSTRING(CAST(CAST(Date AS DATE) AS NVARCHAR),6,10)<SUBSTRING(CAST(CAST(GETDATE() AS DATE) AS NVARCHAR),6,10)
THEN DATEADD(YEAR, 2017-YEAR(ex_date), Date)
ELSE DATEADD(YEAR, 2016-YEAR(ex_date), Date)
END
FROM datetable
WHERE categoryid = 3;
你能證明你怎麼樣輸出看起來像? –