繁体   English   中英

xquery在for循环中返回xml元素?

[英]xquery return xml elements in for loop?

我有以下用于SQL Server 2008表的xquery。

declare @tableName sysname = 'tableName'
declare @colNames xml = (select COLUMN_NAME from INFORMATION_SCHEMA.columns where TABLE_NAME = @tableName for xml path(''), elements)
select @colNames.query('<html><body>
<table>
<tr>
{
    for $c in /COLUMN_NAME
    return data($c)[1]
}
</tr>
</table>
</body></html>
')

但是,它返回以下xml。

<html>
  <body>
    <table>
      <tr>col1col2col3col4col5</tr>
    </table>
  </body>
</html>

预期的结果是

<html>
  <body>
    <table>
      <tr><th>col1</th><th>col2</th><th>col3</th><th>col4</th><th>col5</th></tr>
    </table>
  </body>
</html>

我试图将return data($c)[1]更改为concat("<th>", data($c)[1], "</th>") 但是, <>转义为&lt; &gt;

for $c in /COLUMN_NAME
return element th { data($c)[1] }

要么

for $c in /COLUMN_NAME
return <th>{ data($c)[1] }</th>

或者,您可以直接在查询中执行此操作。

select
  (
  select COLUMN_NAME as '*'
  from INFORMATION_SCHEMA.columns 
  where TABLE_NAME = @tableName
  for xml path('th'), root('tr'), type
  ) as "table"
for xml path('body'), root('html')

要么

select
  (
  select COLUMN_NAME as th
  from INFORMATION_SCHEMA.columns 
  where TABLE_NAME = @tableName
  for xml path(''), type
  ) as "html/body/table/tr"
for xml path('')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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