输出表到Xml:根据特定列值显示属性值

时间:2017-02-01 10:21:12

标签: sql xml tsql

我正在尝试将表输出为Xml。我希望根节点名称为“新建”,表中的每一行都显示为.Could not connect to https://repo.continuum.io/pkgs/pro/noarch/ .. Solving package specifications: . Error: Packages missing in current linux-64 channels: - h5py 2.6.0 np111py35_2 - matplotlib 1.5.3 np111py35_0 - numpy 1.11.2 py35_0 - pandas 0.19.1 np111py35_0 - pillow 3.4.2 py35_0 - pyyaml 3.12 py35_0 - scipy 0.18.1 np111py35_0 - seaborn 0.7.1 py35_0 - setuptools 27.2.0 py35_0 + echo Creating Anaconda environment failed. Creating Anaconda environment failed. + rm -rf /home/anjana/anaconda3/envs/cntk-py35 + exit 1

<member>

如您所见,每个<new> <member source="STORE"> <externalId>111</externalId> <eclubNo>123456</eclubNo> <ssn>195812272796</ssn> <firstName>Loke</firstName > <lastName>Sjögren</lastName> <email>yyy@xxx.se</email> </member> <member source="WEB"> <externalId>222</externalId> <eclubNo>764746</eclubNo> <ssn>222</ssn> <firstName>Loke</firstName > <lastName>Sjögren</lastName> <email>blahblahblah@yahoo.com</email> </member> </new> 都有一个名为 source 的属性。 source的值取决于表中可以包含源值的同名列(如果值为“StoreEntry”则变为“STORE”,如果“WebEntry”变为“WEB”,如上面的片段所示)。如何使用<member>语句获取此Xml?

1 个答案:

答案 0 :(得分:2)

你可以这样试试:

这是一个有效的例子。下次请自己准备(How to create a MCVE):

DECLARE @tbl TABLE(source VARCHAR(100),externalId INT,eclubNo INT,ssn BIGINT,firstName VARCHAR(100),lastName VARCHAR(100),email VARCHAR(100));
INSERT INTO @tbl VALUES
 ('StoreEntry',111,123456,13213213123,'Loke','Sjörgen','yyy@xxx.se')
,('WebEntry',222,34234,443,'Other','Name','email@yyy.se');

- 查询

SELECT CASE WHEN [source]='StoreEntry' THEN 'STORE' ELSE 'WEB' END AS [@source]
      ,externalId
      ,eclubNo
      ,ssn
      ,firstName
      ,lastName
      ,email
FROM @tbl AS YourTable
FOR XML PATH('member'),ROOT('new');

结果

<new>
  <member source="STORE">
    <externalId>111</externalId>
    <eclubNo>123456</eclubNo>
    <ssn>13213213123</ssn>
    <firstName>Loke</firstName>
    <lastName>Sjörgen</lastName>
    <email>yyy@xxx.se</email>
  </member>
  <member source="WEB">
    <externalId>222</externalId>
    <eclubNo>34234</eclubNo>
    <ssn>443</ssn>
    <firstName>Other</firstName>
    <lastName>Name</lastName>
    <email>email@yyy.se</email>
  </member>
</new>