在SQL Server中获取无效的列错误

时间:2014-04-24 22:29:18

标签: sql-server

我有以下查询:

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

2 个答案:

答案 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)

您无法真正使用刚刚定义的列。您的选择是:

  1. 明确重写原始查询(我不会建议 - 太复杂,不太万无一失):
  2. 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'
    
    1. 将数据插入临时表(如果您需要多次访问,这将是一个不错的选择)
    2. 我最喜欢的选项:使用Common Table Expression
    3. ;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'