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

Syntax error when using Convert inside PIVOT

我需要将我的值转换为 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。谁能告诉我完成此操作的正确方法?

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

问题是您正试图在 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