2

我有一个查询,它只提取两列并将其中一列修剪为仅媒体名称。这是查询:

   Select
   [Object],  
   CASE WHEN MsgID = '61' THEN SUBSTRING(Parms,35,6) END AS [MEDIA]
   from JnlDataSection

结果是:

目的
---------
061 声明

媒体
---------
X01180
X01181

如您所见,一个对象有多种媒体。我想要的是一个手动查询,我可以在其中使用对象名称对其进行修改,并使用其所有各自的媒体搜索一个对象,反之亦然。

这是我提出的查询:

  Select
  [Object],  
  CASE WHEN MsgID = '61' THEN SUBSTRING(Parms,35,6) END AS [MEDIA]
  WHERE [OBJECT] = '061 STATEMENTS'
  from JnlDataSection

但是我收到此错误:

Msg 156, Level 15, State 1, Line 5
Incorrect syntax near the keyword 'from'.

请注意:我使用的是 SQL Server Management Studio 2008。

更新

阅读评论后,我尝试了这个查询:

Select
  [Object],  
  CASE WHEN MsgID = '61' THEN SUBSTRING(Parms,35,6) END AS [MEDIA]
 from JnlDataSection
 WHERE [MEDIA] = 'X05219'

它给了我这个错误:

Msg 207, Level 16, State 1, Line 5
Invalid column name 'MEDIA'.

我该如何解决?

4

1 回答 1

1

要扩展@JNK 的建议,如果您想与计算MEDIA列进行比较,您可以选择以下选项:

  1. 重现子句CASE中的表达式:WHERE

    SELECT
      [Object],  
      CASE WHEN MsgID = '61' THEN SUBSTRING(Parms, 35, 6) END AS [MEDIA]
    FROM JnlDataSection
    WHERE CASE WHEN MsgID = '61' THEN SUBSTRING(Parms, 35, 6) END = 'X05219'
    ;
    
  2. 将查询重新定义为公用表表达式

    WITH JnlDataSectionMedia AS (
      SELECT
        [Object],  
        CASE WHEN MsgID = '61' THEN SUBSTRING(Parms, 35, 6) END AS [MEDIA]
      FROM JnlDataSection
    )
    SELECT *
    FROM JnlDataSectionMedia
    WHERE [MEDIA] = 'X05219'
    ;
    

    或(正常)子选择:

    SELECT *
    FROM (
      SELECT
        [Object],  
        CASE WHEN MsgID = '61' THEN SUBSTRING(Parms, 35, 6) END AS [MEDIA]
      FROM JnlDataSection
    ) AS s
    WHERE [MEDIA] = 'X05219'
    ;
    
  3. 使用CROSS APPLY

    SELECT
      j.[Object],
      x.[MEDIA]
    FROM JnlDataSection AS j
    CROSS APPLY (
      SELECT CASE WHEN MsgID = '61' THEN SUBSTRING(Parms, 35, 6) END
    ) AS x ([MEDIA])
    WHERE x.[MEDIA] = 'X05219'
    ;
    
  4. 您还可以将查询定义为视图

    CREATE VIEW JnlDataSectionMedia
    AS
    SELECT
      [Object],  
      CASE WHEN MsgID = '61' THEN SUBSTRING(Parms, 35, 6) END AS [MEDIA]
    FROM JnlDataSection
    ;
    

    之后,您可以像这样随时调用它:

    SELECT [Object], [MEDIA]
    FROM JnlDataSectionMedia
    ;
    

    必要时,您也可以过滤任一列:

    SELECT [Object], [MEDIA]
    FROM JnlDataSectionMedia
    WHERE [MEDIA] = 'X05219'
    ;
    
于 2013-07-15T17:52:43.367 回答