我有一个带有示例值的 XML 列

<error>
  <errorno>BL04002055</errorno>
  <description>Smart Rule PROJECT_COUNTRYCODE_VAL Violated</description>
  <description2>Country Code is required</description2>
  <correction />
</error>
<error>
  <errorno>BL01001973</errorno>
  <description />
  <description2>Error While Saving the Project info</description2>
  <correction />
</error>
<error>
  <errorno>Unable to Create Custom Object</errorno>
  <description />
  <description2>Smart Rule PROJECT_COUNTRYCODE_VAL Violated: Country Code is required
Error While Saving the Project info</description2>
  <correction />
</error>

我想选择 description2 值逗号分隔
select *
--, Response.value(''/error/description2/text()'', 'varchar(8000)') as parsedString
, Response.query('/error/description2/text()') as parsedString
 from #temp

这里有两个问题。
  • 我无法在上面的查询中运行值函数。
  • 使用查询,我得到没有空格或逗号的连接值。所以我需要在连接的值上添加一些空格或逗号。
  • 最佳答案

    SQL Server 没有实现 xPath 函数 string-join ,因此您需要采用两步过程,首先是使用 nodes() 将所有术语提取到行中;

    SELECT  n.value('.', 'VARCHAR(100)') AS parsedString
    FROM    #temp AS t
            CROSS APPLY t.Response.nodes('/error/description2') r (n);
    

    这为您提供了行的值:
    parsedString
    ----------------------------------------------------------------------------
    Country Code is required
    Error While Saving the Project info
    Smart Rule PROJECT_COUNTRYCODE_VAL Violated: Country Code is required
    Error While Saving the Project
    

    然后你可以添加你的分隔符并将它们连接起来,使用 FOR XML PATH(''), TYPE ,最后使用 STUFF 删除第一个分隔符:
    SELECT  STUFF(( SELECT  ',' + n.value('.', 'VARCHAR(100)') AS parsedString
                    FROM    #temp AS t
                            CROSS APPLY t.Response.nodes('/error/description2') r (n)
                    FOR XML PATH(''), TYPE
                ).value('.', 'VARCHAR(MAX)'), 1, 1, '') AS ParsedString;
    

    完整工作示例
    DECLARE @X XML = '<error>
      <errorno>BL04002055</errorno>
      <description>Smart Rule PROJECT_COUNTRYCODE_VAL Violated</description>
      <description2>Country Code is required</description2>
      <correction />
    </error>
    <error>
      <errorno>BL01001973</errorno>
      <description />
      <description2>Error While Saving the Project info</description2>
      <correction />
    </error>
    <error>
      <errorno>Unable to Create Custom Object</errorno>
      <description />
      <description2>Smart Rule PROJECT_COUNTRYCODE_VAL Violated: Country Code is required
    Error While Saving the Project info</description2>
      <correction />
    </error>';
    
    SELECT  STUFF(( SELECT  ',' + n.value('.', 'VARCHAR(100)') AS parsedString
                    FROM    (SELECT @X) AS t (Response)
                            CROSS APPLY t.Response.nodes('/error/description2') r (n)
                    FOR XML PATH(''), TYPE
                ).value('.', 'VARCHAR(MAX)'), 1, 1, '') AS ParsedString;
    

    10-08 16:40