T-SQL 用分号拆分字符串字段产生错误 XML 解析:第 1 行,字符 49,非法名称字符

T-SQL Splitting String field by semi colon produces error XML parsing: line 1, character 49, illegal name character

我正在使用 SQL Server 2014。我将地址作为一个大字符串存储在 table tblAddress 中名为 addr 的列(我无法控制它来自第三方供应商)

addr
--------------------------------------------------
1 Smith Street;My Old Town; Someplace;Pluto;
5 SmokeyStreet;Someoldtown;Someotherplace;;
7 Grove Hill; Someolder town;Someotherplace;Earth

我想提取它,使其看起来像下面分成 4 列:

Addr1            Addr2           Addr3            Addr4
----------------------------------------------------------
1 Smith Street   My Old Town     Someplace        Pluto
5 SmokeyStreet   Someoldtown     Someotherplace
7 Grove Hill     Someolder town  Someotherplace   Earth

我试过:

SELECT  
    CAST('<x>' + REPLACE([addr], ';', '</x><x>') + '</x>' AS XML).value('/x[1]', 'nvarchar(50)') AS Addr1,
    CAST('<x>' + REPLACE([addr], ';', '</x><x>') + '</x>' AS XML).value('/x[2]', 'nvarchar(50)') AS Addr2,
    CAST('<x>' + REPLACE([addr], ';', '</x><x>') + '</x>' AS XML).value('/x[3]', 'nvarchar(50)') AS Addr3,
    CAST('<x>' + REPLACE([addr], ';', '</x><x>') + '</x>' AS XML).value('/x[4]', 'nvarchar(50)') AS Addr4
FROM
    tblAddress;

但我一直收到错误消息:

XML parsing: line 1, character 49, illegal name character

我哪里错了?

与其重复计算,不如考虑使用一次 CROSS APPLY

例子

Select Pos1 = xDim.value('/x[1]' ,'varchar(150)')
      ,Pos2 = xDim.value('/x[2]' ,'varchar(150)')
      ,Pos3 = xDim.value('/x[3]' ,'varchar(150)')
      ,Pos4 = xDim.value('/x[4]' ,'varchar(150)')
 From  YourTable A
 Cross Apply ( values (cast('<x>' + replace((Select replace(A.addr,';','§§Split§§') as [*] For XML Path('')),'§§Split§§','</x><x>')+'</x>' as xml)) )B(xDim)

结果

Pos1             Pos2           Pos3            Pos4
1 Smith Street   My Old Town    Someplace       Pluto
5 SmokeyStreet   Someoldtown    Someotherplace  
7 Grove Hill     Someolder town Someotherplace  Earth