So here's my code that doesn't work:
SET QUOTED_IDENTIFIER ON
DECLARE
@tab char(1) = CHAR(9),
@arg VARCHAR(MAX) = 'N2'
EXEC msdb.dbo.sp_send_dbmail
@profile_name = 'Company Profile',
@recipients = 'randomemail.gmail.com',
@query = 'SET NOCOUNT ON
SELECT
e.EmplName,
FORMAT(SUM(t.ManHrs), @arg) AS [Hrs Logged to Jobs]
FROM EmplCode e JOIN TimeTicketDet t ON e.EmplCode = t.EmplCode
WHERE CAST(t.TicketDate AS DATE) = CAST(GETDATE() AS DATE)
AND t.WorkCntr <> 50
GROUP BY e.EmplName, t.WorkCntr
HAVING SUM(t.ManHrs) < 6
ORDER BY SUM(t.ManHrs)',
@subject = 'Hello',
@query_result_separator = @tab,
@execute_query_database = 'Company DB';
I get the following error when I run it:
Failed to initialize sqlcmd library with error number -2147467259.. If I remove the @arg variable inside @query and instead use
CAST(SUM(t.ManHrs) AS FLOAT)
It works fine, even leaving the declared variable, so I suppose I could do that, but I'm just wondering what the error message even means. Any time I have quotes inside my @query argument, I'm going to have to use variables right? So what's going on? And how can I prevent this in the future? Thanks
...FORMAT(SUM(t.ManHrs),' + @arg +')...?