How to add an attribute to element-centric FOR XML PATH query
Asked Answered
A

1

5

I'm building some HTML to be included in the body of an email and sent using sp_send_dbmail. I'd like to right-align some of the columns. Is there an easy way to do this (short of rewriting it using FOR XML EXPLICIT)?

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>'
Armament answered 23/9, 2010 at 15:7 Comment(0)
H
12

This should do it. Note that you don't need to manually add the <tr> and </tr> tags to your html string. Those are given to you as part of the for xml path('tr'). You probably meant to add </table> to the end instead.

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

Output is:

<table cellpadding=0 cellspacing=0 border=0><tr><td>Column1</td><td>Column2</td><td align="right">Column3</td></tr></table>
Hartman answered 23/9, 2010 at 19:41 Comment(1)
Extremely nice description of FOR XML capabilities can be found here: sqlserverpedia.com/blog/sql-server-bloggers/xml-paths-of-glorySagesagebrush

© 2022 - 2024 — McMap. All rights reserved.