1

我想将此 Case 语句合并到我的 sql 查询中,但我收到此错误:Invalid Column Name: 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()))
4

2 回答 2

3

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

于 2013-07-02T14:39:21.583 回答
0

你没有MsgId从(大概)暴露JnlListA,在这里:

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

因此,您可能只需要添加MsgId到该SELECT子句。如果它不是来自那张桌子,请告诉我们它应该来自哪里。

于 2013-07-02T14:40:39.310 回答