Sql-Server

將 ASCII 字節從 XML 轉換為 VARCHAR

  • February 15, 2019

我有XML包含字元串作為字節數組的數據,我想將其轉換為VARCHARin SQL Server 2012. 範例片段text="2Hallo"和我嘗試的程式碼:

DECLARE @testxml XML = N'
<ProgramWzgSignStates>
   <WzgSignStates>
       <Element>
           <id>AQ_A07_1_280_F3~ZA</id>
           <text>
               <Element>50</Element>
               <Element>72</Element>
               <Element>97</Element>
               <Element>108</Element>
               <Element>108</Element>
               <Element>111</Element>
           </text>
       </Element>
   </WzgSignStates>
</ProgramWzgSignStates>'

SELECT 
Tab.Col.value('id[1]', 'varchar(50)') AS Id,
Tab.Col.value('text[1]', 'nvarchar(MAX)') AS TextAsNVarChar
,Tab.Col.value('text[1]', 'varbinary(MAX)') AS TextAsVarBinary
,Convert(NVARCHAR(255), Tab.Col.value('text[1]', 'varbinary(MAX)')) AS TextUsingConvert
FROM @testxml.nodes('/ProgramWzgSignStates/WzgSignStates/Element') AS Tab(Col);

這導致以下輸出:

Id                 TextAsNVarChar  TextAsVarBinary TextUsingConvert
AQ_A07_1_280_F3~ZA 507297108108111 NULL            NULL

在使用返回時,轉換為將NVARCHAR導致連接的 ascii 程式碼。VARBINARY``NULL

如何將字元串檢索2HalloVARCHAR/ NVARCHAR

我認為您應該解析text/Elements ,以便獲得所需的字元串。

SELECT 
Tab.Col.value('id[1]', 'varchar(50)') AS Id,
Tab.Col.value('text[1]', 'nvarchar(MAX)') AS TextAsNVarChar
,(SELECT CHAR(t.u.value('.','nvarchar(max)'))
       FROM Tab.Col.nodes('text/Element') AS t(u)
       FOR XML PATH('')
)TextAsNVarChar_New
FROM @testxml.nodes('/ProgramWzgSignStates/WzgSignStates/Element') AS Tab(Col)

我曾經FOR XML PATH獲得2Hallo

Id                 TextAsNVarChar    TextAsNVarChar_New
AQ_A07_1_280_F3~ZA 507297108108111   2Hallo

引用自:https://dba.stackexchange.com/questions/115664