2011-07-05 37 views
-1

我正在開發下面的tsql查詢。我如何識別其中包含「1900%」的記錄?如何識別T-SQL中的DATETIME NULL記錄?

SELECT DISTINCT TICKET, COMPLAINT_LEVEL, COMPLETION_DATE, DATE_FILTER, YEAR(DATE_FILTER) AS YEAR_FILTER, MONTH(DATE_FILTER) AS MONTH_FILTER, 
left(datename(month, DATE_FILTER), 3) + ' ''' + 
RIGHT(year(DATE_FILTER), 2) AS SHORT_DATE_FILTER, 
CASE WHEN DATE_FILTER < MONTH_END AND MONTH_END < CURRENT_DATE_END AND COMPLETION_DATE IS NULL THEN DATE_FILTER 
WHEN DATE_FILTER < MONTH_END AND MONTH_END < CURRENT_DATE_END AND 
COMPLETION_DATE IS NOT NULL AND ABS(DATEDIFF(DAY, COMPLETION_DATE, MONTH_END)) >= 1 AND DATE_FILTER < CURRENT_DATE_END THEN DATE_FILTER 
ELSE 0 END AS ROW_TYPE 
FROM #TEMP 
--WHERE row_type = 0 
--line above does not work 

這是我的輸出是什麼樣子 enter image description here

回答

1

似乎沒有日期時間具有空值。

雖然看起來只是檢查row_type。它不會工作,它是一個計算列。您需要將腳本更改爲此以檢查row_type,否則您需要與生成計算列的整個表達式進行比較。

SELECT * FROM (
SELECT DISTINCT TICKET, COMPLAINT_LEVEL, COMPLETION_DATE, DATE_FILTER, YEAR(DATE_FILTER) AS YEAR_FILTER, MONTH(DATE_FILTER) AS MONTH_FILTER, 
left(datename(month, DATE_FILTER), 3) + ' ''' + 
RIGHT(year(DATE_FILTER), 2) AS SHORT_DATE_FILTER, 
CASE WHEN DATE_FILTER < MONTH_END AND MONTH_END < CURRENT_DATE_END AND COMPLETION_DATE IS NULL THEN DATE_FILTER 
WHEN DATE_FILTER < MONTH_END AND MONTH_END < CURRENT_DATE_END AND 
COMPLETION_DATE IS NOT NULL AND ABS(DATEDIFF(DAY, COMPLETION_DATE, MONTH_END)) >= 1 AND DATE_FILTER < CURRENT_DATE_END THEN DATE_FILTER 
ELSE 0 END AS ROW_TYPE 
FROM #TEMP) a 
WHERE YEAR(ROW_TYPE) = 1900 
0

這會工作,以及:

WHERE ROW_TYPE = 0 

但是,正如@t-clausen.dk正確地指出的那樣,ROW_TYPE列不能同SELECT的WHERE子句中引用。通常你會添加一個外部的SELECT,所有內部SELECT的別名都可以訪問到。

+0

它不會在上面的sql中工作。您無法與計算列進行比較。即使如此,它只能在1900年的第一天工作。但根據測試數據,這似乎已經足夠了。 –

+0

數字與'date'數據類型不兼容。但'ROW_TYPE'顯然是'datetime'。我看不出爲什麼你認爲這不適用於上述查詢。這個簡單的例子似乎表明它會:「SELECT * FROM(SELECT GETDATE()UNION ALL SELECT 0)x(d)WHERE d = 0'。查詢返回一行'1900-01-01 00:00:00.000'的值。 –

+0

我認爲你需要閱讀我的解決方案來澄清我的評論 –