sql中的xml元素

时间:2018-06-25 11:00:34

标签: xml tsql

第一次编写TSQL以输出XML。

以下是我尝试输出的XML格式。 enter image description here

我已经开始整理下面的代码-

SELECT              1 as 'PropRecordType'
                    ,a.AssetReference as 'PropCliReference'



FROM  Asset a
LEFT JOIN AssetType at on at.AssetTypeId = a.AssetTypeID



WHERE at.Letable = 1

FOR XML PATH('Property'), 
ROOT ('UESDPropertyDetails');

因此,我很乐意在“属性”部分中添加元素列表。 这是我如何获取“属性”部分中数据的RiskAssessementList部分的方法?

1 个答案:

答案 0 :(得分:0)

我在这里所做的实际上是您的工作(创建测试方案)。试试看:

DECLARE @propTable TABLE(ID INT, eMail VARCHAR(100),ward VARCHAR(100));
INSERT INTO @propTable VALUES(1,'Some@email.com','blah');

DECLARE @AssessmentTable TABLE(ID INT, PropID INT /*fk*/, Code VARCHAR(100),Descr VARCHAR(100));
INSERT INTO @AssessmentTable VALUES(1,1,'GPO','')
                                  ,(2,1,'ASB','001'); 

-查询

SELECT pt.eMail AS PropEMail
      ,pt.ward AS PropWard
      ,(
        SELECT at.Code AS AssessmentCode
              ,at.Descr AS AssessmentDesc
        FROM @AssessmentTable at
        WHERE at.PropID=pt.ID
        FOR XML PATH('RiskAssessment'),ROOT('RiskAssessmentList'),TYPE
       )
FROM @propTable pt
FOR XML PATH('Property'),ROOT('UESDPropertyDetail');

结果

<UESDPropertyDetail>
  <Property>
    <PropEMail>Some@email.com</PropEMail>
    <PropWard>blah</PropWard>
    <RiskAssessmentList>
      <RiskAssessment>
        <AssessmentCode>GPO</AssessmentCode>
        <AssessmentDesc />
      </RiskAssessment>
      <RiskAssessment>
        <AssessmentCode>ASB</AssessmentCode>
        <AssessmentDesc>001</AssessmentDesc>
      </RiskAssessment>
    </RiskAssessmentList>
  </Property>
</UESDPropertyDetail>