2010-09-23 71 views
3

我正在構建一些HTML以包含在電子郵件的正文中並使用sp_send_dbmail發送。我想對齊某些列。有沒有一種簡單的方法來做到這一點(使用FOR XML EXPLICIT來重寫它)?如何將屬性添加到以元素爲中心的FOR XML PATH查詢

declare @html varchar(max) 

set @html = '<table cellpadding=0 cellspacing=0 border=0>' 

set @html += 
    cast(
    (select 
     'Column1' as td, '', 
     'Column2' as td, '', 
     'Column3' as [td align=right] /* Would like to do something like this */ 
    for xml path('tr')) as varchar(max) 
) 

set @html += '</table>' 

回答

10

這應該這樣做。請注意,您不需要手動將<tr></tr>標籤添加到您的html字符串中。那些作爲for xml path('tr')的一部分給你。您可能打算將</table>添加到最後。

declare @html varchar(max) 

set @html = '<table cellpadding=0 cellspacing=0 border=0>' 

set @html += 
    cast(
    (select 
     'Column1' as td, '', 
     'Column2' as td, '', 
     'right' as [td/@align], 'Column3' as td, '' 
    for xml path('tr')) as varchar(max) 
) 

set @html += '</table>' 

select @html 

輸出是:對XML功能

<table cellpadding=0 cellspacing=0 border=0><tr><td>Column1</td><td>Column2</td><td align="right">Column3</td></tr></table> 
+0

極佳的描述可以在這裏找到:http://sqlserverpedia.com/blog/sql-server-bloggers/xml-paths-of-榮耀/ – milivojeviCH 2012-11-28 17:23:48

相關問題