在PIVOT中使用Convert时出现语法错误

时间:2016-02-29 18:38:50

标签: sql sql-server unpivot

我需要将我的值转换为Varchar。我有这个代码:

SELECT Value AS FieldName, [42] AS [KeyID_42],[600] AS [KeyID_600]
FROM
(
  SELECT TransID, Value, FieldName
  FROM 
  (
      SELECT TransID, [ErisaPlanEndsMM], [ErisaPlanEndsDD],
           [MLRAvgLivesNumber], [MLRAvgLivesRptYear]
      FROM tblSQLAdminInventory
  ) p
  UNPIVOT
   (FieldName FOR Value IN 
      (Convert(VarChar(250), [ErisaPlanEndsMM]) AS [ErisaPlanEndsMM],
       Convert(VarChar(250), [ErisaPlanEndsDD]) AS [ErisaPlanEndsDD],
       Convert(VarChar(250), [MLRAvgLivesNumber]) AS [MLRAvgLivesNumber],
       Convert(VarChar(250), [MLRAvgLivesRptYear]) AS [MLRAvgLivesRptYear])
   )AS unpvt
) AS SourceTable
PIVOT
(
MAX(FieldName)
FOR TransID IN ([42],[600])
) AS PivotTable

我收到了错误:

Msg 156, Level 15, State 1, Line 9
Incorrect syntax near the keyword 'Convert'.

我在网上找到的所有内容都是使用CAST的情况,因为用户需要转换为Int。在我的情况下,我想要一切Varchar。谁能告诉我完成这个的正确方法呢?

我应该补充一点,这是一个动态查询,可能包含几十个字段,具体取决于表。上面的代码是针对一个特定表运行时生成的SQL。

1 个答案:

答案 0 :(得分:1)

问题是您正在尝试转换unpivot内部,这是无效的语法。需要将数据之前转换为尝试取消隐藏。

您可以通过将转换放在子查询中来解决此问题:

SELECT TransID, Value, FieldName
FROM 
(
    SELECT TransID, 
       Convert(VarChar(250), [ErisaPlanEndsMM]) AS [ErisaPlanEndsMM], 
       Convert(VarChar(250), [ErisaPlanEndsDD]) AS [ErisaPlanEndsDD],
       Convert(VarChar(250), [MLRAvgLivesNumber]) AS [MLRAvgLivesNumber], 
       Convert(VarChar(250), [MLRAvgLivesRptYear]) AS [MLRAvgLivesRptYear]
    FROM tblSQLAdminInventory
) p
UNPIVOT
(
    FieldName FOR Value IN 
      ([ErisaPlanEndsMM], [ErisaPlanEndsDD], [MLRAvgLivesNumber], [MLRAvgLivesRptYear])
)AS unpvt