Passing Cursor Result to send_dbmail as a Parameter - sql

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.

Related

sp_executesql failing if line ends in \

This code:
EXEC sp_executesql N'
CREATE PROCEDURE [dbo].[a]
(
#VarA NVARCHAR(200), -- Path to exe e.g. e:\blah\blah\
#VarB INT -- 1 to log actions
)
AS
BEGIN
PRINT #VarA
PRINT #VarB
END'
GO
That'll throw an error:
Msg 102, Level 15, State 1, Procedure a, Line 5 [Batch Start Line 0]
Incorrect syntax near ')'.
Msg 137, Level 15, State 2, Procedure a, Line 9 [Batch Start Line 0]
Must declare the scalar variable "#VarB".
If you remove the \ so have e:\blah\blah instead it works; if you add a space after the \ it works - it all seems to be to do with that ...
So - is that a bug?
Thanks, Dr. Michael Dye.
This is using the Backslash (Line Continuation) (Transact-SQL) feature. This means that the lines below:
(
#VarA NVARCHAR(200), -- Path to exe e.g. e:\blah\blah\
#VarB INT -- 1 to log actions
)
Are being parsed as
(
#VarA NVARCHAR(200), -- Path to exe e.g. e:\blah\blah\#VarB INT -- 1 to log actions
)
As a result, the error.
Therefore, don't end you're line with a \ and then immediately preceed it with a line break or carriage return and line break. As this is a comment, you could simply put a . at the end:
(
#VarA NVARCHAR(200), -- Path to exe e.g. e:\blah\blah\.
#VarB INT -- 1 to log actions
)

Replace function requires 3 arguments

I am trying to fetch data from SQL to excel and it is giving me the below error
My Query in SQL Server
DECLARE #Delimiter Char(1)
SET #Delimiter = CHAR(9)
EXEC MSDB.dbo.sp_Send_DBMail
#profile_name = 'K2MailSetup',
#Recipients='abs#test.com',
#Subject='Extraction Report',
#Body='Hi,
Please find attached extraction report as required. ',
#Query='set nocount on;Select Coalesce(replace(replace(A.[type], char(10), ''), char(13), ''),'') as Type FROM [EU_OTH_REG].[dbo].[TBL_EU_OTH_TXN_REG_RSDS] A',
#Attach_Query_Result_As_File = 1,
#Query_Result_Header = 1,
#Query_Attachment_Filename = 'Report.csv',
#Query_Result_Separator = #Delimiter,
#query_result_width =32767,
#query_result_no_padding=1
========================================================================
It is giving me below error
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 517
Query execution failed: Msg 105, Level 15, State 1, Server MYKULK2DB01Q\MSSQLSTG, Line 1
Unclosed quotation mark after the character string ') as Type
FROM [EU_OTH_REG].[dbo].[TBL_EU_OTH_TXN_REG_RSDS] A
'.
Msg 102, Level 15, State 1, Server MYKULK2DB01Q\MSSQLSTG, Line 1
Incorrect syntax near ') as Type
FROM [EU_OTH_REG].[dbo].[TBL_EU_OTH_TXN_REG_RSDS] A
========================================================================
The strange thing is that when I just run the query it provides me result but when I try to create report out of it by using the above excel steps and parameters it gives me error.
You need to check the quote in the #Query variable.
I replaced it in the following;
#Query='set nocount on;Select Coalesce(replace(replace(A.[type], char(10), ''''), char(13), ''''),'''') as Type FROM [EU_OTH_REG].[dbo].[TBL_EU_OTH_TXN_REG_RSDS] A'
From the docs: SQL Server Replace
The syntax for REPLACE() goes as follows:
REPLACE ( string_expression , string_pattern , string_replacement )
As you can see, all parameters should be in string format. Make sure all parameters are encased in '' for your script to work.

How to solve incorrect syntax near 'xml'?

I'm working on an administration program, and when writing one of it's features I encountered this error.
Here's the code.
CODE:
create procedure wIaTertiDemo
#sesiune varchar(50),
parXML xml
as
begin try
declare #utilizator varchar(500)
exec wIaUtilizator #sesiune #utilizator output
select codfiscal, denumire as #dentert, adresa
from tertiDemo
for xml raw
--create table tertiDemo(codfiscal varchar(50), denumire varchar(500), adresa varchar(500)
end try
BEGIN CATCH
DECLARE #mesajEroare varchar(1000)
SET #mesajEroare = ERROR_MESSAGE()+ '(' +OBJECT_NAME(##PROCID) + ')'
RAISERROR (#mesajEroare, 16,1)
END CATCH
Errors:
Msg 102, Level 15, State 1, Procedure wIaTertiDemo, Line 1 [Batch Start Line 0]
Incorrect syntax near 'xml'
Msg 102, Level 15, State 1, Procedure wIaTertiDemo, Line 6 [Batch Start Line 0]
Incorrect syntax near '#utilizator'
Msg 102, Level 15, State 1, Procedure wIaTertiDemo, Line 8 [Batch Start Line 0]
Incorrect syntax near '#dentert'
parXML xml
Should be:
#parXML xml
And
exec wIaUtilizator #sesiune #utilizator output
should be:
exec wIaUtilizator #sesiune, #utilizator output
And
denumire as #dentert
should be:
denumire as dentert

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).