简体   繁体   中英

SQL “for XML” and built-in functions like “comment()”

I'm writing an SQL select statement which returns XML. I wanted to put in some comments and found a post asking how to do this. The answer seemed to be the "comment()" function/keyword. So, my code looks broadly like this:

select  ' extracted on tuesday ' as 'comment()',
        (select top 5 id from MyTable for xml path(''),type)
for xml path('stuff')

...which returns XML as follows:

<stuff>
  <!-- extracted on tuesday -->
  <id>0DAD4B42-CED6-4A68-AB7D-0003E4C127CC</id>
  <id>24BD0E5F-8B76-43FF-AEEA-0008AA911ADD</id>
  <id>AAFF5BB0-BFFB-4584-BACC-0009684A1593</id>
  <id>0581AF24-8C30-408C-9A48-000A488133AC</id>
  <id>01E2306D-296A-4FF7-9263-000EEFF42230</id>
</stuff>

In the process of trying to find out more about "comment()", I discovered "data()" as well.

select top 5 id as 'data()' from MyTable for xml path('')

Unfortunately, the names make searching for information on these functions very difficult.

Can someone point me at the documentation on their usage, as well as any other similar functions ?

Thanks,

Edit:

Another would appear to be "processing-instruction(blah)".

Example:

select  'type="text/css" href="style.css"' as 'processing-instruction(xml-stylesheet)',
        (select top 5 id from MyTable for xml path(''),type)
for xml path('stuff')

Results:

<stuff>
  <?xml-stylesheet type="text/css" href="style.css"?>
  <id>0DAD4B42-CED6-4A68-AB7D-0003E4C127CC</id>
  <id>24BD0E5F-8B76-43FF-AEEA-0008AA911ADD</id>
  <id>AAFF5BB0-BFFB-4584-BACC-0009684A1593</id>
  <id>0581AF24-8C30-408C-9A48-000A488133AC</id>
  <id>01E2306D-296A-4FF7-9263-000EEFF42230</id>
</stuff>

Here is the link to the BOL info: Columns with the Name of an XPath Node Test . This details the functionality you are interested in. (It can indeed be a pain to find)

Also you can find quick functional examples here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM