2013-03-15 102 views
0

我有以下xquery Sql server 2008表。xquery返回for循環中的xml元素?

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;

+0

的(http://stackoverflow.com/questions/7086393/create-html-table-with-sql-for [與FOR XML SQL創建HTML表]可能的複製-xml) – Shnugo 2016-09-14 14:42:44

+0

嗨,如果這對你來說仍然很有趣,尤其是由於下面的註釋(*是否可以將表的數據附加到列標題下的xml中?*),我想指出你到一個[我剛剛回答的相關問題的回答](http://stackoverflow.com/a/39487565/5089204) – Shnugo 2016-09-14 14:44:38

回答

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

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

另外,您可以在您的查詢直接做到這一點。

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('') 
+0

太好了。是否有可能將表的數據附加到列標題下的XML?我想我需要爲它創建一個新問題。 – ca9163d9 2013-03-15 15:54:14

+0

http://stackoverflow.com/questions/15436826/convert-to-html-using-xquery – ca9163d9 2013-03-15 16:01:13

+0

@NickW現在沒時間了,但我之前做了類似的事情。看看這個:http://stackoverflow.com/a/7087899/569436 – 2013-03-15 16:05:14