title: Format query output into an html table
body: <p>I need the sql query result sent by e-mail to be in readable form. A change to html would allow to create results in the table. I need help implementing html in the code below.</p>
  
  <pre><code>USE msdb
  go
  
  SET QUOTED_IDENTIFIER OFF
  SET ANSI_NULLS ON
  
  IF EXISTS (select Kod, Nazwa from DATABASE.dbo.Towar where Kod NOT LIKE '%?%' and AsId IN (205, 304, 289, 321, 306, 217, 261) and Aktywny = 1)
  BEGIN
      EXEC sp_send_dbmail @profile_name='PROFILE',
          @recipients='myadres@email.com',
          @query_result_header=0,
          @attach_query_result_as_file=0,
          @query="select Kod, Nazwa from DATABASE.dbo.Towar where Kod NOT LIKE '%?%' and AsId IN (205, 304, 289, 321, 306, 217, 261) and Aktywny=1 ORDER BY Kod",
          @body_format='text',
          @subject='warning';
  END;
  
  GO
  </code></pre>
  
  <p>The example contained in the 'MgSam' post <a href="https://stackoverflow.com/questions/7070053/convert-a-sql-query-result-table-to-an-html-table-for-email">Convert a SQL query result table to an HTML table for email</a> actually solves the problem of convert to html and create table. However, I have no idea how to implement the 'if' condition.</p>
  
  <p>According to the MgSam guidelines - the following code works - but if the query does not return data - the email is sent.</p>
  
  <pre><code>SET QUOTED_IDENTIFIER OFF
  SET ANSI_NULLS ON
  
  DECLARE @html nvarchar(MAX);
  
  EXEC spQueryToHtmlTable @html = @html OUTPUT,  @query = "select Kod, Nazwa from DATABASE.dbo.Towar where Kod NOT LIKE '%?%' and AsId IN (205, 304, 289, 321, 306, 217, 261) and Aktywny = 1", @orderBy = N'ORDER BY Kod';
  
  EXEC msdb.dbo.sp_send_dbmail
      @profile_name='PROFILE',
      @recipients='my@email.com',
      @subject = 'WARNING',
      @body = @html,
      @body_format = 'HTML',
      @query_no_truncate = 1,
      @attach_query_result_as_file = 0;
  </code></pre>