具有宽度限制的XML元素值

时间:2017-05-18 05:31:58

标签: sql xml sql-server-2008 tsql for-xml-path

我是XML新手并尝试使用customer table在SQL Server 2008中解决以下问题。

NAME列具有固定宽度,因此需要将值(客户名称)分成多个表示。

请参阅:

  • NAME index="1" ...
  • NAME index="2" ...

知道如何解决这个问题吗?

谢谢你, 安

<PARTNER>
    <NAME index="1">XEXSY SMALL REALTY LLC</NAME>
    <NAME index="2">AA/NAX TEEEENERGY</NAME>
    <PARTNRTYPE>703884</PARTNRTYPE>
    <ADDRESS>
       <ADDRLINE index="1">544 PACIFIC BLVD</ADDRLINE>
       <CITY>LONG BEACH</CITY>
       <COUNTRY>US</COUNTRY>
       <POSTALCODE>07740</POSTALCODE>
    </ADDRESS>
</PARTNER>

1 个答案:

答案 0 :(得分:0)

这种设计很糟糕。如果你有一点机会改变这个,你应该......

如果你必须坚持这一点,你可以这样试试:

DECLARE @mockup TABLE(Name VARCHAR(100),PartnerType INT,Addr VARCHAR(100),City VARCHAR(100));
INSERT INTO @mockup VALUES
 ('This is a very long name which needs to be splitted in smaller parts'
  ,12345
  ,'And this address is very long too, the person has a really long address...'
  ,'Washington')
,('ShortName'
  ,12345
  ,'ShortAddress'
  ,'New York');

- 您可以设置切片的长度TOP(20)是硬编码的,并设置了部件数量的上限。

DECLARE @PartLenght INT=20;

- 查询将获取一个数字表(计数表即时,然后使用FOR XML PATH()创建带有嵌套的XML你需要。

WITH Tally AS
(
    SELECT TOP(20) ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS Nr 
    FROM master..spt_values 
)
SELECT (
        SELECT Nr AS [NAME/@index]
              ,SUBSTRING(m.Name,Nr+((Nr-1) * (@PartLenght-1)),@PartLenght) AS [NAME]
        FROM Tally
        WHERE LEN(SUBSTRING(m.Name,Nr+((Nr-1) * (@PartLenght-1)),@PartLenght))>0
        FOR XML PATH(''),TYPE
       )
      ,m.PartnerType AS [PARTNERTYPE]
      ,(
          SELECT    
          (
            SELECT Nr AS [ADDRLINE/@index]
                  ,SUBSTRING(m.Addr,Nr+((Nr-1) * (@PartLenght-1)),@PartLenght) AS [ADDRLINE]
            FROM Tally
            WHERE LEN(SUBSTRING(m.Addr,Nr+((Nr-1) * (@PartLenght-1)),@PartLenght))>0
            FOR XML PATH(''),TYPE
          )
         ,City AS [CITY]
         FOR XML PATH('ADDRESS'),TYPE
      )
FROM @mockup AS m
FOR XML PATH('PARTNER')

结果

<PARTNER>
  <NAME index="1">This is a very long </NAME>
  <NAME index="2">name which needs to </NAME>
  <NAME index="3">be splitted in small</NAME>
  <NAME index="4">er parts</NAME>
  <PARTNERTYPE>12345</PARTNERTYPE>
  <ADDRESS>
    <ADDRLINE index="1">And this address is </ADDRLINE>
    <ADDRLINE index="2">very long too, the p</ADDRLINE>
    <ADDRLINE index="3">erson has a really l</ADDRLINE>
    <ADDRLINE index="4">ong address...</ADDRLINE>
    <CITY>Washington</CITY>
  </ADDRESS>
</PARTNER>
<PARTNER>
  <NAME index="1">ShortName</NAME>
  <PARTNERTYPE>12345</PARTNERTYPE>
  <ADDRESS>
    <ADDRLINE index="1">ShortAddress</ADDRLINE>
    <CITY>New York</CITY>
  </ADDRESS>
</PARTNER>