MS SQL 2005 HTML Query Systax Issues

Below I have some SQL which performs a query and places in HTML format.  I am running into some systax issues.  Scroll down through the code to find my comments in bold where the two syntax errors are occurring.

DECLARE @Body NVARCHAR(MAX),
            @TableHead VARCHAR(1000),
            @TableTail VARCHAR(1000)



SET @TableTail = '</table></body></html>' ;
SET @TableHead = '<html><head>' + '<style>'
    + 'td {border: solid black;border-width: 1px;padding-left:5px;padding-right:5px;padding-top:1px;padding-bottom:1px;font: 11px arial} '
    + '</style>' + '</head>' + '<body>' + 'Report generated on : '
    + CONVERT(VARCHAR(50), GETDATE(), 106)
    + '<br> <table cellpadding=0 cellspacing=0 border=0>'
    + '<tr> <td bgcolor=#E6E6FA><b>Job Name</b></td>'
    + '<td bgcolor=#E6E6FA><b>Time Run</b></td>'
    + '<td bgcolor=#E6E6FA><b>Duration</b></td>'
    + '<td bgcolor=#E6E6FA><b>Job Status</b></td>'
    + '<td bgcolor=#E6E6FA><b>Job Outcome</b></td>'
    + '<td bgcolor=#E6E6FA><b>Rn</b></td></tr>';

SET  @Body = ( SELECT    td = SJ.name, '',
                         td = CONVERT(VARCHAR,DATEADD(S,(sjh.run_time/10000)*60*60 /* hours */  
                             +((sjh.run_time - (sjh.run_time/10000) * 10000)/100) * 60 /* mins */  
                                 + (sjh.run_time - (sjh.run_time/100) * 100), '',  /* secs */
   ----------      First error message below is due to the Convert date above... I assume the concatenation is an issue, but not positive.
   ----------       Msg 102, Level 15, State 1, Line 25
   ----------      Incorrect syntax near '='.

                   td = CONVERT(DATETIME,RTRIM(sjh.run_date),113)),100), '',
                   td = STUFF(STUFF(REPLACE(STR(sjh.run_duration,7,0),' ','0'),4,0,':'),7,0,':'), '',
                   td = CASE WHEN enabled=1 THEN 'Enabled'  
                           ELSE 'Disabled'  
                           END, '',
                   td = CASE WHEN SJH.run_status=0 THEN 'Failed'
                                 WHEN SJH.run_status=1 THEN 'Succeeded'
                                 WHEN SJH.run_status=2 THEN 'Retry'
                                           WHEN SJH.run_status=3 THEN 'Cancelled'
                                 ELSE 'Unknown'  
                          END, '',
                   td = ROW_NUMBER() OVER (PARTITION BY SJ.NAME ORDER BY SJH.RUN_DATE desc), ''
            FROM   sysjobhistory SJH  
                         JOIN   sysjobs SJ
                 ON   SJH.job_id=sj.job_id  
               WHERE  step_id=0  
                 AND  DATEADD(S,  
                     (run_time/10000)*60*60 /* hours */  
                            +((run_time - (run_time/10000) * 10000)/100) * 60 /* mins */  
                              + (run_time - (run_time/100) * 100)  /* secs */,  
                              CONVERT(DATETIME,RTRIM(run_date),113)) >= DATEADD(d,-1,GetDate())  
                         AND category_id <> '109'

----------  Second issue is on the "t' after the and statement below.  This is part of the nested function to query only the latest row from ----------  a  group
                         AND enabled = 1) t
                            WHERE t.rn = 1
                  FOR   XML RAW('tr'),
                  ELEMENTS
            )

SELECT  @Body = @TableHead + ISNULL(@Body, '') + @TableTail
66chawgerAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Lee SavidgeCommented:
I would imagine this is a problem:

SELECT    td = SJ.name, 

Open in new window


td is not a variable. What are you trying to achieve with this? I can see it builds a table in SQL, but really, this should be done in the server side code, not SQL. SQL should return the data to a server side application which populates the data into a formatted SQL string.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
PortletPaulEE Topic AdvisorCommented:
There are MANY issues, some I cannot figure out without your knowledge.

This is as far as I could get:
SET @Body = (
      SELECT
            SJ.name
          , ''
          , CONVERT(varchar, DATEADD(S, ((sjh.run_time / 10000) * 60 * 60), [DateColumn]), @style-missing) /* hours */
            + ((sjh.run_time - (sjh.run_time / 10000) * 10000) / 100) * 60 /* mins */
            + (sjh.run_time - (sjh.run_time / 100) * 100)  /* secs */
          , ''
          , CONVERT(datetime, sjh.run_date, 113)
          , ''
          , ''
          , CASE
                  WHEN enabled = 1 THEN
                        'Enabled'
                  ELSE
                        'Disabled'
            END
          , ''
          , CASE
                  WHEN SJH.run_status = 0 THEN
                        'Failed'
                  WHEN SJH.run_status = 1 THEN
                        'Succeeded'
                  WHEN SJH.run_status = 2 THEN
                        'Retry'
                  WHEN SJH.run_status = 3 THEN
                        'Cancelled'
                  ELSE
                        'Unknown'
            END
          , ''
          , ROW_NUMBER() OVER (PARTITION BY SJ.NAME ORDER BY SJH.RUN_DATE DESC)
          , ''
      FROM SJ
      INNER JOIN SJH
            ON sj.x = sjh.y
      JOIN sysjobs SJ
            ON SJH.job_id = sj.job_id
      WHERE step_id = 0
      AND DATEADD(S,
      (run_time / 10000) * 60 * 60 /* hours */
      + ((run_time - (run_time / 10000) * 10000) / 100) * 60 /* mins */
      + (run_time - (run_time / 100) * 100)  /* secs */,
      CONVERT(datetime, RTRIM(run_date), 113)) >= DATEADD(D, -1, GETDATE())
      AND category_id <> '109'

      AND enabled = 1
/*
) t
                            WHERE t.rn = 1
                  FOR   XML RAW('tr'),
                  ELEMENTS
*/

)

SELECT
      @Body = @TableHead + ISNULL(@Body, '') + @TableTail

Open in new window


I removed all the "td =" references, there is a style number and a parenthesis missing (see @style-missing)
line 9 is a complete guess (it was weird in the original)
then toward the end I could make no sense of lines 49 to 52
66chawgerAuthor Commented:
Yes this appears unorthodox.  I am simply (take simply with a grain of salt) attempting to format query results and distribute through dbmail.  Lee, I am right there with you, I could go SSRS route, or other as you stated... it becomes more convoluted when you are not dealing with aggregates and having to do data manipulation such as the date formatting and such.  Query by itself works fine, again just trying a simple way of getting it in a format to email through dbmail after query results are rendered.
Big Business Goals? Which KPIs Will Help You

The most successful MSPs rely on metrics – known as key performance indicators (KPIs) – for making informed decisions that help their businesses thrive, rather than just survive. This eBook provides an overview of the most important KPIs used by top MSPs.

PortletPaulEE Topic AdvisorCommented:
>>"Query by itself works fine"

I'm sorry but which query is working fine? Can you supply the query that is working?
66chawgerAuthor Commented:
USE MSDB
SELECT * 
FROM
(
SELECT  SJ.name AS [Job Name]
         ,CONVERT(VARCHAR,DATEADD(S,(sjh.run_time/10000)*60*60 /* hours */  
          +((sjh.run_time - (sjh.run_time/10000) * 10000)/100) * 60 /* mins */  
          + (sjh.run_time - (sjh.run_time/100) * 100)  /* secs */
         ,CONVERT(DATETIME,RTRIM(sjh.run_date),113)),100) AS [Time Run]
         ,Duration = STUFF(STUFF(REPLACE(STR(sjh.run_duration,7,0),' ','0'),4,0,':'),7,0,':')
         ,CASE WHEN enabled=1 THEN 'Enabled'  
               ELSE 'Disabled'  
          END [Job Status]
         ,CASE WHEN SJH.run_status=0 THEN 'Failed'
                     WHEN SJH.run_status=1 THEN 'Succeeded'
                     WHEN SJH.run_status=2 THEN 'Retry'
                     WHEN SJH.run_status=3 THEN 'Cancelled'
               ELSE 'Unknown'  
          END [Job Outcome]
          ,ROW_NUMBER() OVER (PARTITION BY SJ.NAME ORDER BY SJH.RUN_DATE desc) as rn
FROM   sysjobhistory SJH  with (nolock)
JOIN   sysjobs SJ with (nolock)
ON     SJH.job_id=sj.job_id  
WHERE  step_id=0  
AND    DATEADD(S,  
  (run_time/10000)*60*60 /* hours */  
  +((run_time - (run_time/10000) * 10000)/100) * 60 /* mins */  
  + (run_time - (run_time/100) * 100)  /* secs */,  
  CONVERT(DATETIME,RTRIM(run_date),113)) >= DATEADD(d,-1,GetDate())  
AND category_id <> '109'
AND enabled = 1) t
WHERE t.rn = 1

Open in new window

Vitor MontalvãoMSSQL Senior EngineerCommented:
66chawger, do you still need help with this question?
66chawgerAuthor Commented:
No, I was able to use what I had listed above.
66chawgerAuthor Commented:
I did end up splitting the two out, the HTML table and the SQL.   I was able to accomplish what I needed with a bit what I originally posted, however, Lee is correct, in the long run it is better to have them separated.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft SQL Server 2005

From novice to tech pro — start learning today.