【问题标题】:SQL to populate values in xml listSQL 在 xml 列表中填充值
【发布时间】:2014-05-15 18:47:08
【问题描述】:

在 SQL Server 存储过程中,我需要使用来自两个不同表的数据生成 xml。在下面的示例中,EPI 类型的患者编号来自一个表,MRN 类型的患者编号来自另一个表。要创建 xml,我使用 UNION 来组合来自两个不同选择语句的记录,然后使用“FOR XML PATH”。有没有不同的方法——比如使用两个 select 子查询而不使用 UNION?

<Patients>
  <Patient>
    <Number>1234</Number>
    <NumberType>EPI</NumberType>
  </Patient>
  <Patient>
    <Number>5678</Number>
    <NumberType>MRN</NumberType>
  </Patient>
</Patients>

提前致谢。

【问题讨论】:

  • 您真的想要一个包含在“Patient”元素中的数字和类型列表吗?这些表格是否以任何方式相关,例如通过患者 ID?您是否在问是否可以在一个患者元素下列出所有数字和类型?上述 xml 示例是否是您的真正目标?
  • 如果你想从 2 个不同的表中获取数据,我认为联合会很好。检查此链接也blog.sqlauthority.com/2009/02/12/…
  • @Tans - UNION 语句是我发现完成我想做的事情的最佳方法。感谢您的回复。
  • @mdisibio - 是的,提供的 xml 是必需的输出。节点 Number 和 NumberType 中的值是从通过 PatientId 连接的不同表中提取的。

标签: sql-server xml tsql


【解决方案1】:

如果我理解您对我的问题的回答,那么您并没有真正加入 PatientId 上的表格,您只是创建了两个表格中所有数据的列表,并且您不需要按患者对记录进行分组。

是的,UNION 是完成单个列表的最简单方法。

但是,由于您要输出 xml,因此根据您的问题,可以在没有 UNION 的情况下使用另一种方法: 假设您有两个可能看起来像这样的表:

CREATE TABLE SrcA (PatientId int, NumberA int, TypeA varchar(16));
CREATE TABLE SrcB (PatientId int, NumberB int, TypeB varchar(16));

使用这样的示例值(注意每个表如何有一条记录而不是另一条记录):

INSERT INTO SrcA VALUES(100, 1234, 'EPI'), (200, 2222, 'EPI'), (400, 4444, 'EPI');
INSERT INTO SrcB VALUES(100, 5678, 'MRN'), (200, 2121, 'MRN'), (300, 3131, 'MRN');

然后是下面的查询:

          SELECT
                 (SELECT SA.NumberA AS Number, SA.TypeA AS NumberType WHERE SA.NumberA IS NOT NULL FOR XML PATH('Patient'), TYPE),
                 (SELECT SB.NumberB AS Number, SB.TypeB AS NumberType WHERE SB.NumberB IS NOT NULL FOR XML PATH('Patient'), TYPE)
            FROM SrcA SA
 FULL OUTER JOIN SrcB SB ON SA.PatientId = SB.PatientId
         FOR XML PATH(''), ROOT('Patients')

将产生:

<Patients>
  <Patient>
    <Number>1234</Number>
    <NumberType>EPI</NumberType>
  </Patient>
  <Patient>
    <Number>5678</Number>
    <NumberType>MRN</NumberType>
  </Patient>
  <Patient>
    <Number>2222</Number>
    <NumberType>EPI</NumberType>
  </Patient>
  <Patient>
    <Number>2121</Number>
    <NumberType>MRN</NumberType>
  </Patient>
  <Patient>
    <Number>4444</Number>
    <NumberType>EPI</NumberType>
  </Patient>
  <Patient>
    <Number>3131</Number>
    <NumberType>MRN</NumberType>
  </Patient>
</Patients>

【讨论】:

    猜你喜欢
    • 2023-03-12
    • 2014-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-01
    • 1970-01-01
    • 2013-07-01
    相关资源
    最近更新 更多