XML自动或XML路径

本文关键字:XML 路径 | 更新日期: 2023-09-27 17:50:00

执行以下查询

SELECT     AssessmentFileGUID as '@FileId',AssessmentFileTypeId as '@FileTypeId',AssessmentFileName
FROM         rat.AssessmentFile where AssessmentId=17 
for xml path('File'),root('Files')

给出如下结果:

<Files>
  <File FileId="2A23D836-612F-418E-BDE8-F182C5432A0D" FileTypeId="1">
    <AssessmentFileName>File-123213.pdf</AssessmentFileName>
  </File>
  <File FileId="CDA853B9-C587-4365-BAF5-972F8D217BAC" FileTypeId="2">
    <AssessmentFileName>File-343455.png</AssessmentFileName>
  </File>
</Files>

但是我需要它的格式如下:

<Files>
  <File FileId="2A23D836-612F-418E-BDE8-F182C5432A0D" FileTypeId="1">File-123213.pdf</File>
  <File FileId="CDA853B9-C587-4365-BAF5-972F8D217BAC" FileTypeId="2">File-343455.png</File>
</Files>

XML自动或XML路径

指定作为data()内容的列,它应该放在正确的位置:

declare @T table (
    AssessmentFileGUID uniqueidentifier not null,
    AssessmentFileTypeId int not null,
    AssessmentFileName varchar(max) not null,
    AssessmentId int not null
)
insert into @T(AssessmentFileGUID,AssessmentFileTypeId,AssessmentFileName,
     AssessmentId) values
('2A23D836-612F-418E-BDE8-F182C5432A0D',1,'File-123213.pdf',17),
('CDA853B9-C587-4365-BAF5-972F8D217BAC',2,'File-343455.png',17)
SELECT     AssessmentFileGUID as '@FileId',AssessmentFileTypeId as '@FileTypeId',
     AssessmentFileName as 'data()' //Change here
FROM         @T where AssessmentId=17 
for xml path('File'),root('Files')
结果:

<Files>
    <File FileId="2A23D836-612F-418E-BDE8-F182C5432A0D" FileTypeId="1">File-123213.pdf</File>
    <File FileId="CDA853B9-C587-4365-BAF5-972F8D217BAC" FileTypeId="2">File-343455.png</File>
</Files>

不确定,但试试

SELECT     
    AssessmentFileGUID as '@FileId',
    AssessmentFileTypeId as '@FileTypeId',
    AssessmentFileName as "File/text()"
FROM         
    rat.AssessmentFile 
where 
    AssessmentId = 17 
FOR XML PATH('File'), ROOT('Files')