我有以下查询:
TimeStamp列中的值为201403240004
,因此以下函数会以以下格式对其进行转换:2014-03-24 00:04:00.000
SELECT CONVERT(DATETIME,
SUBSTRING([TimeStamp],1,4)+'-'+SUBSTRING([TimeStamp],5,2)+'-'
+SUBSTRING([TimeStamp],7,2)+' '+SUBSTRING([TimeStamp],9,2)+':'
+SUBSTRING([TimeStamp],11,2)+':00.000') AS MessageDate
FROM Table
WHERE MessageDate = '2014-03-24 00:04:00.000'
当我在WHERE子句中尝试使用MessageDate
时,为什么在sqlserver中出现无效的列名错误?如何在WHERE子句中使用转换后的MessageDate
?
答案 0 :(得分:1)
在select
子句之后处理where
语句时,您无法直接使用计算列。使用计算列的一种方法是将其包装在另一个选择中:
SELECT * FROM (
SELECT CONVERT(DATETIME,
SUBSTRING([TimeStamp],1,4)+'-'+SUBSTRING([TimeStamp],5,2)+'-'
+SUBSTRING([TimeStamp],7,2)+' '+SUBSTRING([TimeStamp],9,2)+':'
+SUBSTRING([TimeStamp],11,2)+':00.000') AS MessageDate
FROM Table) innerQuery
WHERE MessageDate = '2014-03-24 00:04:00.000'
或者您可以在where子句中使用完整计算。
答案 1 :(得分:1)
您无法真正使用刚刚定义的列。您的选择是:
SELECT CONVERT(DATETIME,
SUBSTRING([TimeStamp],1,4)+'-'+SUBSTRING([TimeStamp],5,2)+'-'
+SUBSTRING([TimeStamp],7,2)+' '+SUBSTRING([TimeStamp],9,2)+':'
+SUBSTRING([TimeStamp],11,2)+':00.000') AS MessageDate
FROM Table WHERE CONVERT(DATETIME,
SUBSTRING([TimeStamp],1,4)+'-'+SUBSTRING([TimeStamp],5,2)+'-'
+SUBSTRING([TimeStamp],7,2)+' '+SUBSTRING([TimeStamp],9,2)+':'
+SUBSTRING([TimeStamp],11,2)+':00.000') = '2014-03-24 00:04:00.000'
;WITH data AS (SELECT CONVERT(DATETIME,
SUBSTRING([TimeStamp],1,4)+'-'+SUBSTRING([TimeStamp],5,2)+'-'
+SUBSTRING([TimeStamp],7,2)+' '+SUBSTRING([TimeStamp],9,2)+':'
+SUBSTRING([TimeStamp],11,2)+':00.000') AS MessageDate
FROM Table
) SELECT * FROM data
WHERE MessageDate = '2014-03-24 00:04:00.000'