Can Execute Procedure But Job That Runs Procedure Errors? - sql-server

I have a procedure that pulls data from my database and uses MSDB.DBO.sp_send_dbmail to send out e-mails. The procedure itself runs without a hitch when I use 'EXEC myprocedure'. But when I set up a job for the procedure, the job fails with the following error
'Error formating query, probably invalid parameters [SQLState
42000](Error 22050). The step failed'
There is one step in the job with the TSQL statement 'EXEC myprocedure', using the database that my procedure is stored on. Does anyone know what could be causing this error?
Update
I've narrowed the problem down. It's something with the Exchange server I use. I was using a domain address (ie. mail.mycompany.com) as the 'Server name' under Database Mail's account configuration wizard. I was unable to send e-mails to listservs and external users using this domain address. I talked to our Exchange guy and he recommended using the actual IP address of one of the mail servers (ie. 10.123.53.53). That fixed the problem with listservs and external users, but now I am unable to send e-mails when I run my procedure using a job (the procedure itself executes properly when I manually run it). Does anyone know what criteria on our Exchange server I will need to change to fix this?

This is like to be a permissions issue. It is impossible from the information given to specify exactly what permission is the problem, but a TSQL job step will run under the context of the Server Agent Service Account, so ensure that that account has SELECT permissions to the tables that are being used to build the query, and then make sure that it has permissions to the profile that you are using within Database Mail.

The problem was with the #query parameter used by sp_send_dbmail. For some reason, my SQL Server Agent account (which was a domain administrator) was denied access to use sp_send_dbmail with the #query parameter. I ended up dropping the #query parameter altogether and putting everything in the #body parameter. The #body parameter became a concatenation of regular text and what returned from a SELECT query.

Related

sp_send_dbmail not executing in execute sql task without throwing any error

I am newbie to SSIS. I am facing an issue executing sp_send_dbmail in one of my stored procedures which is being run by Execute SQL task in SSIS. Main problem is, it is not throwing any error and completing successfully even though profile with which I am running this SP doesn't exist. I suspect there is a configuration issue but I am not able to diagnose it.
I have found that SMTP is not configured on my staging server. Can it be the only reason? Even if it is, it should at least throw an error, but in logs I do not see any error messages for the same.
Also, if I am running this SP directly through SQL, I get "Profile doesn't exists" error. But when I am running same SP through SSIS (execute sql task), then it is executing successfully.
Any guidance on this issue can be a great help.
This is how I am calling sp_send_dbmail.
EXEC msdb.dbo.sp_send_dbmail
#profile_name = 'Stagging Trigger',
#recipients = 'myemailID#test.com',
#subject = 'this is the SP to send mail from SP'
sp_send_dbmail only queues up the mail. Does not attempt to deliver, does not validate the email profile, cannot raise any of the errors you complain are missing.
Read here how to check the status of emails queued: Check the Status of E-Mail Messages Sent With Database Mail:
USE msdb ;
GO
-- Show the subject, the time that the mail item row was last
-- modified, and the log information.
-- Join sysmail_faileditems to sysmail_event_log
-- on the mailitem_id column.
-- In the WHERE clause list items where danw was in the recipients,
-- copy_recipients, or blind_copy_recipients.
-- These are the items that would have been sent
-- to danw.
SELECT items.subject,
items.last_mod_date
,l.description FROM dbo.sysmail_faileditems as items
INNER JOIN dbo.sysmail_event_log AS l
ON items.mailitem_id = l.mailitem_id
WHERE items.recipients LIKE '%danw%'
OR items.copy_recipients LIKE '%danw%'
OR items.blind_copy_recipients LIKE '%danw%'
GO
More articles on the topic:
Troubleshooting Database Mail Failures
Complete Troubleshooting Guide for SQL Server Database Mail
Your error is pretty clear in what is required. First off, create a profile and note down all the values that you will input on the wizard. This guide will help you create the profile correctly.
Once you have verified that the dbmail profile has been setup, its time to put it to test. If you cant send out email through the stored proc, I would want to talk to the AD admin or the person responsible for setting up the email server. This is to make sure that you can anonymously send emails and to take care of any potential relay server issues. Hope this helps.

Using stored procedure in openrowset throws login_mapping error

Because I need to fill a view with dynamic data, I wrote a stored procedure to collect the data and use select from OPENROWSET('SQLNCLI','server=....;trusted_connection=yes','EXEC Stored_Procedure') as the view definition.
As far as I know you can't use variables in your view definition so that's why I choose this route.
The stored procedure collects data from a linked server source combined with native SQL Server data. The linked_server has the appropriate permissions setup for the remote user and can be successfully queried from outside SQL Server.
That works very well in a local context but when I try to use the view in a PostGreSQL foreign-table I get an ODBC error. The first errors involved the permission to execute the stored procedure by the caller's user account. After that I get stuck. It seems the connection with the server has sufficient access permissions but the OPENROWSET call to execute the stored procedure does not (no login_mapping exists).
However, if I change the SQL in the OPENROWSET command to a simple select statement (select * from db.schema.table) it works fine.
I tried to change the server in de OPENROWSET to a datasource to the local server itself, with the remote user to impersonate, but with no luck either. The same login_mapping error.
My guess is that this has something to do with the fact that the users security context is not the one used by the OPENROWSET command?
I have looked around a lot but was not able to find a solution. Can you help me?

Calling SSIS with SSISDB implementation from SQL Server Service broker

The requirement is to call a web service through SSIS and calling the SSIS from a SQL Server Service Broker activated stored procedure.
Here is what I have currently doing:
Queue
CREATE QUEUE [schema].[ProccessingQueue] WITH STATUS = ON , RETENTION = OFF , ACTIVATION ( STATUS = ON , PROCEDURE_NAME = [schema].[usp_ProccessingQueueActivation] , MAX_QUEUE_READERS = 10 , EXECUTE AS N'dbo' ), POISON_MESSAGE_HANDLING (STATUS = ON)
My stored procedure:
ALTER PROCEDURE [schema].[usp_ProccessingQueueActivation]
WITH EXECUTE AS CALLER
AS
BEGIN
SET NOCOUNT ON;
<snip declaration>
BEGIN
BEGIN TRANSACTION;
WAITFOR
(
RECEIVE TOP (1)
#ConversationHandle = conversation_handle,
#MessageBody = CAST(message_body AS XML),
#MessageTypeName = message_type_name
FROM [schema].[ProccessingQueue]
), TIMEOUT 5000;
<snip awasome stuff>
EXEC dbo.RunSSIS <param>
DECLARE #ReplyMessageBody XML = #MessageBody;
SEND ON CONVERSATION #ConversationHandle MESSAGE TYPE [type] (#ReplyMessageBody);
END
<handle error>
COMMIT TRANSACTION;
END
END
Now here is what RunSSIS stored procedure looks like
ALTER PROCEDURE [dbo].[RunSSIS]
<params>
AS
BEGIN
DECLARE #exec_id BIGINT
EXEC [SSISDB].[catalog].[create_execution]
#package_name=N'<SSIS_package>',
#folder_name=N'<folder>',
#project_name=N'<projectName>',
#use32bitruntime=FALSE,
#reference_id=NULL,
#execution_id=#exec_id OUTPUT
EXEC [SSISDB].[catalog].[set_execution_parameter_value]
#exec_id,
#object_type=30,
#parameter_name=N'<param_Name>',
#parameter_value=<param>
SELECT #exec_id
EXEC [SSISDB].[catalog].[start_execution] #exec_id
END
Now this will throws the below exception in event-viewer as the Sql service broker activation security context isn't recognized in SSISDB environment.
The activated proc
'[schema].[usp_ProccessingQueueActivation]' running on
queue '' output the
following: 'The current security context cannot be reverted. Please
switch to the original database where 'Execute As' was called and try
it again.'
To resolve the problem I have tried those following approach
So I follow this link
http://www.databasejournal.com/features/mssql/article.php/3800181/Security-Context-of-Service-Broker-Internal-Activation.htm
and created a User with a self signed certificate (thinking that it
is user that doesn't has permission). But it is returning same error,
digging deeper I found that [internal].[prepare_execution] in
SSISDB has "REVERT" statement in line no 36 that throws the error as
it doesn't like Impersonation at all.
I tried to move the RunSSIS stored procedure to SSISDB and try to call it from activation stored procedure, it was shoot down as SSISDB it doesn't allow any user with SQL Server auth, It needs to have a Windows auth and User created by Certificate obviously doesn't has windows credential.
My question is
Am I on the correct path? I certainly doesn't anticipate using 2 component of SQL server together would be that difficult.
If not in correct approach what would be best approach to call a service from Service broker? I have seen "External Activation" for SQL Server Service broker but haven't explored is yet. But I would try to stick to something that lives inside server environment and scale-able, and don't like the idea of installing different component in prod environment (it is always a overhead for support personal,as there is one more point which can fail)
I am using Windows auth and my credential has sys_Admin access.
I think you can take out the "WITH EXECUTE AS CALLER" and everything (the proc and then the package that ends up getting called) will be run under the security context of the Service Broker. As long as that context has the permissions to do what you want to do, you should be fine.
I have not used a Service Broker in this way, but I do the same thing with jobs fired off by the SQL Agent. As long as the Agent's security context has the permissions needed in the procs/packages everything runs fine. We use network accounts for our services so it all works between servers as well.
This has a code smell of tight coupling and my first instinct is to decouple the queue, the DB that houses the proc, and the SSIS execution into a PowerShell script. Have the script get the messages from service broker then call SSISDB on a different connection without wrapping [catalog].[create_execution] and [catalog].[set_execution_parameter_value] in a stored proc. You can still run this script directly from Agent.
This approach gives you the most flexibility with regard to security contexts, if one of the components moves to a different server, if something is named differently in dev/QA, or technologies change (Azure ServiceBus instead of Broker for instance). You can also get creative with logging/monitoring.

Unable to call stored procedure from linked server

I am facing a strange issue. I have a linked server on ServerB for ServerA
Now, when I am calling a stored procedure from ServerB like
EXEC [ServerA].[Db].[dbo].[SpName] #Param1 #param2
I am getting error that
The EXECUTE permission was denied on the object 'SpName', database 'Db', schema 'dbo'.
But now when I am executing below query it is returning me result:
SELECT *
FROM [ServerA].[Db].[dbo].[tblName]
I don't know that why I am not able to execute stored procedure from ServerB. I am Db_Owner on both the server.
Screenshot of Linked server security
Linked server catalog
If a linked server query fails, the things to check are (in rough order of probability):
Try logging in locally on the linked server to test access directly. If you have no local access, obviously you won't have it through the link either.
Verify the correct credentials as used when accessing the linked server, and not another user you're not expecting. You can check this with EXEC ('SELECT USER_NAME(), SUSER_NAME()') AT [Server]; if the user name is not what you're expecting, check your linked server definition for the correct login mappings. If you can't access the server at all (any query fails), you have other problems (like Kerberos authentication issues if you're using integrated authentication).
Perform a sanity check that you're accessing the correct server with EXEC ('SELECT ##SERVERNAME') AT [Server]. The network name of a linked server can be changed using sp_setnetname, so the name you use to a access the server isn't necessarily the machine name.
If all else fails, dropping and recreating the linked server definition is always an option, but obviously this could disrupt production work.

SQL Server : sp_send_dbmail never queues email when calling stored procedure

I've got a SQL job that is set up to run sp_send_dbmail and attach the results of a stored procedure as a csv file to the email. This job was running up until a week and a half ago.
Full disclosure: I made a change to the stored procedure around that time. The stored procedure was previously looking at a table in one linked server and is now looking at a table in another linked server.
I am able to take the code out of the job and run it successfully in a query window, I'm also able to execute the stored procedure successfully in a query window without the sp_send_dbmail call. Additionally, the job executes on schedule and reports success, and I see no error messages in the job history. I've included the code that is in the job to run the procedure and send mail below:
USE msdb
GO
EXEC msdb.dbo.sp_send_dbmail
#profile_name = 'SMail',
#recipients = 'xxxx#example.com',
#query = 'EXEC [REP01].[Mktg_Reporting].[dbo].DailyC2C',
#subject = 'Daily Call History',
#query_result_separator=',',
#query_result_no_padding=1,
#query_result_header=0,
#attach_query_result_as_file = 1,
#exclude_query_output=1,
#query_attachment_filename='Calls.csv';
I didn't change any of this code since I created the job, I only made the change in the stored procedure so that it looked at a different linked data source. Any kind of assistance is appreciated.
Edit: I also checked the sysmail_mailitems table and found no messages queued for the current day each time I run the job manually, wanted to make sure I included that detail.
I just looked a little bit deeper into this, Pondlife was on the right track regarding a permissions issue. I looked a bit deeper after my initial reply to him and realized that the NT AUTHORITY\SYSTEM user was not set up to properly access the linked server. I've since fixed the problem.

Resources