如何在T-SQL中识别DATETIME NULL记录?

时间:2011-07-05 15:26:41

标签: tsql datetime null

我正在开发下面的tsql查询。如何识别其中包含“1900%”的记录?

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

3 个答案:

答案 0 :(得分:2)

WHERE DATEPART(year, ROW_TYPE) = 1900

http://msdn.microsoft.com/en-us/library/ms174420.aspx

答案 1 :(得分: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

答案 2 :(得分:0)

这也可行:

WHERE ROW_TYPE = 0

但是,正如@t-clausen.dk已正确指出的那样,ROW_TYPE列不能在同一SELECT的WHERE子句中引用。通常你会添加一个外部SELECT,内部SELECT的所有别名都可以访问它。