title: sp_send_dbmail Incorrect syntax near '<'
body: <p>I'm having a problem sending a HTML formatted email from SQL server.</p>
  
  <p>With the following section of code I get a <code>"Line 1, incorrect syntax near '&lt;'"</code> error.</p>
  
  <pre><code>SET @tableHTML =
      '&lt;H1&gt;Progress Report&lt;/H1&gt;' +
      '&lt;table border="1"&gt;' +
      '&lt;tr&gt;' +
                  '&lt;th&gt;Project Name&lt;/th&gt;' +
                  '&lt;th&gt;Platform&lt;/th&gt;' +
                  '&lt;th&gt;Due By&lt;/th&gt;' +
                  '&lt;th&gt;Current Status&lt;/th&gt;' +
                  '&lt;th&gt;Current State&lt;/th&gt;' +
      '&lt;/tr&gt;' +
      CAST (  
                  ( 
                          SELECT
                                  td = [Project Name],    ' ',
                                  td = Platform,  ' ',
                                  td = [Due By],  ' ',
                                  td = [Current Status],  ' ',
                                  td = [Current State],   ' '
      FROM [dbo].[table_name]
      ORDER BY [Current Status] DESC
      FOR XML PATH('tr'), TYPE
                ) AS NVARCHAR(MAX) ) +
      '&lt;/table&gt;' ;
  </code></pre>
  
  <p>I cant seem to pin it to anything in particular? Any Idea's?</p>
  
  <p>Thanks</p>
  
  <p>Update 1:</p>
  
  <p>Ok I've run the code in a debug session and have checked the contents of @tableHTML, the contents looks fine and it gets populated with the expected data from my Table.</p>
  
  <p>Meaning the errors coming in from somewhere else, so I've copied the whole query this time.</p>
  
  <pre><code>DECLARE @tableHTML NVARCHAR(MAX);
  
  SET @tableHTML =
      '&lt;h1&gt;Progress Report&lt;/h1&gt;' +
      '&lt;table border="1"&gt;' +
      '&lt;tr&gt;' +
                  '&lt;th&gt;Project Name&lt;/th&gt;' +
                  '&lt;th&gt;Platform&lt;/th&gt;' +
                  '&lt;th&gt;Due By&lt;/th&gt;' +
                  '&lt;th&gt;Current Status&lt;/th&gt;' +
                  '&lt;th&gt;Current State&lt;/th&gt;' +
      '&lt;/tr&gt;' +
      CAST 
          (   
                  ( 
                          SELECT
                                  td = [Project Name],    '',
                                  td = Platform,  '',
                                  td = [Due By],  '',
                                  td = [Current Status],  '',
                                  td = [Current State],   ''
      FROM [dbo].[table_name]
      ORDER BY [Current Status] DESC
      FOR XML PATH('tr'), TYPE
                ) AS NVARCHAR(MAX) ) +
      '&lt;/table&gt;';
  
  EXEC msdb.dbo.sp_send_dbmail
      @profile_name = 'db_mail_account',
      @recipients = 'example@example.com',
      @subject = 'Daily Project Tracking Report',
      @query = @tableHTML,
      @body_format = 'HTML';
  </code></pre>
  
  <p>Thanks again.</p>