SQL Sending attach query in email as .csv - sql

I am trying to send an query as an attached .CSV in a email. Here is what I have.
EXEC msdb.dbo.sp_send_dbmail #recipients='bdorner#fascinations.net',
#profile_name= 'MyMailProfile',
#subject='new Items',
#body='New Items',
#query= 'select itemlookupcode, * from Item where
(datecreated BETWEEN DATEADD(DAY, - 100, CURRENT_TIMESTAMP) AND DATEADD(day, - 0, CURRENT_TIMESTAMP))
',
#attach_query_result_as_file=1
#query_attachment_filename = 'test.csv'
I keep getting a error Msg 102, Level 15, State 1, Line 11
Incorrect syntax near '#query_attachment_filename'.
I do have an email that send out a query in a body of an email. If that code will help let me know.
Thank you for the Help,
Brian

You are missing a comma :
#attach_query_result_as_file=1**,**
#query_attachment_filename = 'test.csv'
When you get a syntax error, always look for syntax problems in your query!

You're missing a comma after the #attach_query_result_as_file. That's why you get a syntax error pointing at the next line after.

Related

SQL profile name error when executing job

I'm trying to make a scheduled job, so that on the day 25 of every month it sends an e-mail with some information. The code I have right now is:
EXEC msdb.dbo.sp_send_dbmail
#profile_name = 'Main DB Mail profile',
#recipients = 'myemail#mydomain.net',
#subject = 'PG25',
#query = N'SELECT CONVERT(date, docdata), adoc, nome, etotal, aprovado FROM fo
WHERE aprovado LIKE "0"
AND pdata BETWEEN DATEADD(yy, DATEDIFF(yy, 0, GETDATE()), 0) AND DATEFROMPARTS(YEAR(GETDATE()), MONTH(GETDATE()), 25)',
#attach_query_result_as_file = 1,
#query_attachment_filename = 'results.txt'
but when I execute this code I get this error:
Msg 14607, Level 16, State 1, Procedure msdb.dbo.sysmail_verify_profile_sp, Line 42 [Batch Start Line 5]
Profile name is not valid
Any thoughts on how I can get this to work?
You need to make sure that profile name you are calling has to exist in Database Mail. In order to check, do the following:
Expand Management within your instance;
Then, right click and Configure Database Mail;
After this, if you already have a profile defined, you can choose the 4th option to check the profile name. Otherwise, you need to define a new one (careful on the profile name you choose because it has to match to the one you're calling);

Passing Cursor Result to send_dbmail as a Parameter

I've never worked with cursors before, and upon reading, this may not be the best approach, so by all means, makes suggestions.
I am attempting to pass the result set of a cursor to a query. Here's what I have so far:
DECLARE #PM varchar(50),
#c1 as CURSOR
SET #c1 = CURSOR FOR
SELECT PM
FROM PMtable
OPEN #c1;
FETCH NEXT FROM #c1 INTO #PM;
WHILE ##FETCH_STATUS = 0
BEGIN
DECLARE #emailBody nvarchar(max)
SET #emailBody = 'SELECT * FROM othertable WHERE PM = ' + #PM + ' ORDER BY PM';
EXEC msdb.dbo.sp_send_dbmail
#recipients = 'me#me.com',
#subject = 'test',
#query = #emailBody;
FETCH NEXT FROM #c1 INTO #PM;
END
CLOSE #c1;
DEALLOCATE #c1;
The idea is to send the #emailBody query result set as an email for every result in the cursor. For example, say the cursor returns three results: Bob, Jim, and Joe. I want to loop run the #emailBody query for each result from the cursor and send an email for each result.
When I run the query as is, I receive an error saying:
Msg 22050, Level 16, State 1, Line 0 Error formatting query, probably
invalid parameters
Msg 14661, Level 16, State 1, Procedure
sp_send_dbmail, Line 504 [Batch Start Line 0]
Query execution failed:
Msg 207, Level 16, State 1, Server SERVER, Line 9 Invalid column name
'Bob'.
Msg 207, Level 16, State 1, Server SERVER, Line 1 Invalid
column name 'Bob'.
I have no clue what's going on. Any ideas?
You need to add '':
SET #emailBody='SELECT * FROM othertable WHERE PM = ''' + #PM + ''' ORDER BY PM';
Be aware of possible SQL Injection.
How it works:
Msg 207, Level 16, State 1, Server SERVER, Line 9 Invalid column name 'Bob'.
SELECT * FROM othertable WHERE PM = Bob ORDER BY PM
vs.
SELECT * FROM othertable WHERE PM = 'Bob' ORDER BY PM
Please keep in mind that ORDER BY PM for one value does not change anything.

Correct use of case (error with then)

Can anyone understand why I am getting this error for the below line of code? Please let me know!
Msg 156, Level 15, State 1, Line 52
Incorrect syntax near the keyword 'then'.
Slight modification of this post: How do I add hyphens to this line of code? For instance the format I am getting is PTEE032981. How do I get PT-EE-032981?
Please let me know if this can be answered in this post.
case when (MU.Number like '%co-load%' then SUBSTRING(UPPER(REPLACE(Mu.Number,'-','')) ,
PATINDEX('%[nw]t[A-Z][A-Z][0-9][0-9][0-9][0-9][0-9]%',UPPER(REPLACE(Mu.Number,'-',''))),10))
else ME.MovementReference end as [MovementReference],
No need for a starting parenthesis:
case
when MU.Number like '%co-load%'
then SUBSTRING(UPPER(REPLACE(Mu.Number, '-', '')), PATINDEX('%[nw]t[A-Z][A-Z][0-9][0-9][0-9][0-9][0-9]%', UPPER(REPLACE(Mu.Number, '-', ''))), 10)
else ME.MovementReference
end as [MovementReference],

Error in Openquery Stored Procedure

To keep this as simple as possible I have just copied the line of code causing an error. I'm trying to run a openquery in a stored procedure and keep getting the following error:
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near '*'.
I'm pretty sure it is to do with where I have quotations but I really need a second pair of eyes as I have tried all sorts of combinations:
SET #SQL_ResultID = 'SELECT * FROM OPENQUERY([23-SQL3000], ''SELECT ResultID FROM [Portfolio].[dbo].[Program] P INNER JOIN [Portfolio].[dbo].[Results] A ON P.ProgramID = A.ProgramID WHERE ProgramName = ''''' + #P + ''''' AND ResultsName = ''''' + #A + ''''''')';
Thanks in advance

Sending File through database Mail

I am trying to sending a file through Database mail , when i execute the query below without #query option mail is triggered but when i include the #query option i get the error mentioned.
if ##rowcount >0
EXEC msdb.dbo.sp_send_dbmail #profile_name = ' Errormail',#recipients='arunkumarb#mobiusservices.in;',
#subject = 'A new Record created in the SSORunError Log Table' ,
#body = 'A new Record created in the SSORunError Log Table' ,
#query = 'select * from ip',
#attach_query_result_as_file = 1,
#query_result_width = 4000,
#query_attachment_filename = 'Details.txt'
Error Message :
Msg 22050, Level 16, State 1, Line 0
Error formatting query, probably invalid parameters
Msg 14661, Level 16, State 1, Procedure sp_send_dbmail, Line 504
Query execution failed: Msg 208, Level 16, State 1, Server , Line 1
Invalid object name 'ip'.
Thanks in advance
Try using fully qualified name for the table:
SELECT * FROM yourDatabase.yourSchemaName.ip
You can also set #execute_query_database parameter of your call to sp_send_dbmail to contain the name of your database (although I think that using fully qualified name should be enough).