如何在SQL查询中包含Case语句

时间:2013-07-02 14:37:29

标签: sql sql-server case

我想在我的sql查询中包含这个Case语句,但是我收到了这个错误:列名无效:MsgID。有没有人有任何关于代码如何运行此错误的建议?请注意我使用的是SQL Server management studio 2008。

案例陈述:

    CASE WHEN MsgID = '1' THEN SUBSTRING(Parms,1,6) +' Was removed from:'
    WHEN MsgID = '2' THEN 'This Move List has been cleared of all its media'
    ELSE '' -- Optional Else
    END AS [RemovalPath],

原始查询:

    ;WITH CTE AS
    (
    SELECT  CONVERT(DATETIME,LEFT([Date],8)+' '+
                         SUBSTRING([Date],10,2)+':'+
                         SUBSTRING([Date],12,2)+':'+
                         SUBSTRING([Date],14,2)+'.'+
                         RIGHT([Date],3)) [Date],
        ItemId,
        Parms,
        [OBJECT]
   FROM (  SELECT  ItemId,
                CONVERT(VARCHAR(18),[Date]) [Date],
                Parms,
                [OBJECT]
        FROM JnlList
        WHERE UserCode = 'Automation') A
   )
   SELECT  ItemId,
    CONVERT(DATE,[Date]) [Date],
    CONVERT(VARCHAR(10),[Date],108) AS [Time],
    SUBSTRING(Parms,1,6) +' Was removed from:' RemovalPath,
    [OBJECT] [Move List:]
   FROM CTE
   WHERE [Date] >= CONVERT(DATE,DATEADD(DAY,-4,GETDATE()))

查询给我错误:

  WITH CTE AS
  (
  SELECT  CONVERT(DATETIME,LEFT([Date],8)+' '+
                         SUBSTRING([Date],10,2)+':'+
                         SUBSTRING([Date],12,2)+':'+
                         SUBSTRING([Date],14,2)+'.'+
                         RIGHT([Date],3)) [Date],
        ItemId,
        MsgID,
        Parms,
        [OBJECT]
 FROM (  SELECT  ItemId,
                CONVERT(VARCHAR(18),[Date]) [Date],
                Parms,
                [OBJECT]
        FROM JnlList
        WHERE UserCode = 'Automation') A
 )
 SELECT  ItemId, MsgID,
    CONVERT(DATE,[Date]) [Date],
    CONVERT(VARCHAR(10),[Date],108) AS [Time],
    CASE WHEN MsgID = '1' THEN SUBSTRING(Parms,1,6) +' Was removed from:'
    WHEN MsgID = '2' THEN 'This Move List has been cleared of all its media'
    ELSE '' -- Optional Else
    END AS [RemovalPath],
    [OBJECT] [Move List:]
 FROM CTE
 WHERE [Date] >= CONVERT(DATE,DATEADD(DAY,-4,GETDATE()))

2 个答案:

答案 0 :(得分:3)

导致问题的不是case语句,它是CTE声明 - 内部MsgId语句中没有SELECT列,因此您不能将其包含在外部的列列表中。

答案 1 :(得分:0)

您不会将MsgId(可能)JnlList展示为A,此处:

FROM (  SELECT  ItemId,
            CONVERT(VARCHAR(18),[Date]) [Date],
            Parms,
            [OBJECT]
    FROM JnlList
    WHERE UserCode = 'Automation') A

因此,您可能只需要将MsgId添加到该SELECT子句中。如果它不是来自该表,请告诉我们它的来源。