在SQL FOR XML中格式化XML

时间:2014-07-28 17:07:27

标签: sql-server tsql

以下TSQL代码旨在以XML格式发出数据。以下代码:

SELECT l.wlst_Name [Name]
     , pid.wpid_Number AS [Value]
     , pid.wpid_IsPrimary AS [IsPrimary]
FROM dbo.tb_W_PhoneInternetData AS pid
        INNER JOIN dbo.tb_W_Lists AS l ON pid.wpid_wlst_Type_fk = l.wlst_pk
ORDER BY l.wlst_Name, pid.wpid_IsPrimary DESC
FOR XML RAW('Data'),TYPE

返回以下数据,这是OK ....但是

<Data Name="Email" Value="kevin@myemail.com" IsPrimary="1" />
<Data Name="Fax" Value="21950121" IsPrimary="1" />
<Data Name="ID Number" Value="123435456m" IsPrimary="0" />
<Data Name="Mobile" Value="99977500" IsPrimary="1" />
<Data Name="Phone" Value="23977500" IsPrimary="1" />
<Data Name="Tax No" Value="737 0443 41" IsPrimary="0" />
<Data Name="Website" Value="asdf" IsPrimary="0" />

....但我需要以下格式:

<Data Name="Email" IsPrimary="1">kevin@myemail.com</Data>
<Data Name="Fax" IsPrimary="1" >21950121</Data>
<Data Name="ID Number" IsPrimary="0" />123435456m</Data>
<Data Name="Mobile" IsPrimary="1" >99977500</Data>
<Data Name="Phone" IsPrimary="1" >23977500</Data>
<Data Name="Tax No" IsPrimary="0" >737 0443 41</Data>
<Data Name="Website" IsPrimary="0" >asdf</Data>

?我该怎么办?

2 个答案:

答案 0 :(得分:2)

您应该可以使用FOR XML PATH执行此操作 - 类似这样的内容:

SELECT 
    l.wlst_Name AS '@Name',
    pid.wpid_IsPrimary AS '@IsPrimary',
    pid.wpid_Number AS 'text()'
FROM   
    dbo.tb_W_PhoneInternetData AS pid
INNER JOIN 
    dbo.tb_W_Lists AS l ON pid.wpid_wlst_Type_fk = l.wlst_pk
ORDER BY 
    l.wlst_Name, pid.wpid_IsPrimary DESC
FOR XML PATH('Data'), ROOT('AllData')

基本上,您需要使用以@符号开头的列别名来选择要用作属性的内容。

更新:我更新了我的回复 - 我一直在寻找的(并且无法立即找到)是... AS 'text()',它基本上产生相同的输出(列的值)作为文字文本输出 - 没有任何XML元素打开/结束标记)作为@MikaelEriksson提到的“通配符”字符。

答案 1 :(得分:2)

正如@marc_s所写 - 使用FOR XML PATH。要获得准确的结果,您可以尝试以下方法:

CREATE TABLE #test(
    Name        VARCHAR(10),
    Value       VARCHAR(100),
    IsPrimary   BIT
)

INSERT INTO #test (Name, Value, IsPrimary) VALUES
('Email', 'kevin@myemail.com', 1),
('Fax', '21950121', 1),
('ID Number', '123435456m', 0),
('Mobile', '99977500', 1),
('Phone', '23977500', 1),
('Tax No', '737 0443 41', 0),
('Website', 'asdf', 0)


SELECT
    'Data/@Name'        = Name,
    'Data/@IsPrimary'   = IsPrimary,
    'Data'              = Value
FROM #test
FOR XML PATH(''), ROOT('All'), TYPE

DROP TABLE #test

-- Result
<All>
  <Data Name="Email" IsPrimary="1">kevin@myemail.com</Data>
  <Data Name="Fax" IsPrimary="1">21950121</Data>
  <Data Name="ID Number" IsPrimary="0">123435456m</Data>
  <Data Name="Mobile" IsPrimary="1">99977500</Data>
  <Data Name="Phone" IsPrimary="1">23977500</Data>
  <Data Name="Tax No" IsPrimary="0">737 0443 41</Data>
  <Data Name="Website" IsPrimary="0">asdf</Data>
</All>

更新: @Mikael Eriksson suggested星级通配符。下面的另一个版本:

SELECT
    '@Name'        = Name,
    '@IsPrimary'   = IsPrimary,
    '*'             = Value
FROM #test
FOR XML PATH('Data'), ROOT('All'), TYPE