I was running into an issue when creating and implementing a new SQL server agent job to run and email the results of a simple query:
EXEC ms.dbo.sp_send_dbmail
#profile_name = 'Main DB Mail Profile',
#recipients = 'test#myemail.com',
#subject = 'Basket Report',
#query = N'Select Store, Date, Sum(Amount) as DailyTotal, COUNT(CAST(Trans as varchar(30))+CAST(Register as Varchar(30))) as DistinctTransactions
From BasketAnalysis
Where Date = dateadd(day,datediff(day,1,GETDATE()),0)
GROUP BY Store, Date
ORDER BY Store ASC;',
#attach_query_result_as_file = 1,
#query_attachment_filename = 'BasketReport.txt'
I kept running into a mysterious error message in the history log for the task.
Executed as user: NT AUTHORITY\NETWORK SERVICE. Error formatting
query, probably invalid parameters [SQLSTATE 42000] (Error 22050). The
step failed.
Has anyone had any luck getting more information on these errors and how to resolve them?
Digging around, I found a large number of different potential solutions, that I thought I would try to compile some of them here.
User Permissions: The SQL Server Agent user needs to have sufficient privileges to be able to execute and email. The user needs to have the DatabaseMailUserRole (under msdb user mapping) server role. The SQL Configuration Manager gives you the ability to view and adjust the Server Agent user if necessary, experimenting with a Server Agent exclusive user can be helpful!
Run the query in a new query window: Dumb as this is, I totally neglected to run the query outside of the job itself at first. I realized this, and this gave me some more error information than what was being logged in the Server Agent history.
Check your email parameters: This is my problem, but I was following this tutorial but was getting this error because I neglected to include the '#execute_query_database' parameter in my query. Adding that, pointing to my relevant database, was the missing piece.
Related
I have two servers (A, B) linked together. On server A I have a stored procedure that accesses a table found on server B. I am accessing the table in the following fashion:
SELECT
LoggedAt,
ReturnDuration
FROM [serverB].[databaseName].[dbo].[tableName]
WHERE LoggedAt BETWEEN #StartTime AND #EndTime
AND ReturnDuration IS NOT NULL
The job is a single line that invokes the stored procedure:
EXEC [dbo].[storedProcedureName]
When running the stored procedure manually, it succeeds without any errors. However, when I put the stored procedure in a job and attempt to execute it, I get the following error messages:
The job failed. The job was invoked by User domainName\userName. The last step to run was step 1 (stepName). The job was requested to start at step 1 (stepName).
Executed as user: NT AUTHORITY\SYSTEM. Login failed for user domainName\SQL01AGENT. [SQLSTATE 28000] (Error 18456). The step failed.
Looking for help online, I managed to discover the error may be due to domainName\SQL01AGENT not being added as a valid login on server B. After adding that login and granting it the correct user mappings (mapped to my database on server B with db_datareader, db_dataowner and public roles) with Login status set to enabled, the job still failed with the same error.
Another solution I found was to run the step as myself instead of the server agent. However that gave me a different error that "Access to the remote server is denied because the current security context is not trusted. [SQLSTATE 42000] (Error 15274). The step failed."
Any help would be greatly appreciated!
If you haven't already you might ask your DBA to add a linked server to ServerB under Server Objects -> Linked Servers
I'm executing a SP that dynamically builds a global temp table of data gathered from multiple databases. At the end of this SP is this line of code:
Exec msdb.dbo.sp_send_dbmail
#profile_name = #dbmailProfileName,
#recipients = #emailRecipents,
#subject = #subject,
#body = #body,
#query = 'Select * From tempdb..##MyTempTable'
This SP works perfectly when I execute it manually, however, when I let my Server Agent Job run it, it fails with the following error:
Message
Executed as user: WORKGROUP\MyServer2016$. Failed to initialize sqlcmd library with error number -2147467259. [SQLSTATE 42000] (Error 22050) Failed to initialize sqlcmd library with error number -2147467259. [SQLSTATE 42000] (Error 22050). The step failed.
Commenting out #query portion of the SP will work fine, but that's useless since I need the data emailed.
I knew it was some kind of security issue, but my lack of DBA skills defeated me here. However, I found a workaround solution which worked, not exactly what I was looking for, but it works.
Editing the Job Step to include an Execute As with my working login:
Execute As Login='MyUser'
GO
exec DBNAME.dbo.SPNAME
GO
Revert
GO
Since MyUser could run this thing manually, I executed as my login.
I was getting this same error then, after numerous trial and error attempts, another error popped up:
The EXECUTE permission was denied on the object 'xp_sysmail_format_query',
database 'mssqlsystemresource', schema 'sys'.
I added the user to the public role in the master database then added this permission for the user:
grant execute on xp_sysmail_format_query to [myuser]
It seems that Database Mail relies on this stored proc. After doing this, the email job works fine. Note: I run the job as a designated user.
Did you try use the #execute_query_database parameter? If that doesn't work, try to add the Sql Server Agent account to the Sql Server as a sysadmin
The initial situation:
I'm using Microsoft SQL Server 2008 (SP4) - 10.0.6241.0 (X64),Enterprise Edition (64-bit) on a virtual machine (clustered instance).
Under Policy Management ...
... I defined the following condition:
ExecuteSql('Numeric', '
USE [msdb];
SELECT [enabled]
FROM [dbo].[sysjobs]
WHERE [name] = ''updSTAT Agentur- und Bildempfangsdatum'';
')
The policy using this condition is active, evaluation mode is set to "On schedule".
Finally I set up an alert which sends a message to an operator, if error 34052 is raised.
So far so good!
If I evaluate the policy manually, everything is working fine. If the policy is evaluated on schedule the following error is raised (error 229, severity 14 in policy history, not in the job agent's history):
The SELECT permission was denied on the object 'sysjobs', database
'msdb', schema 'dbo'.
The job which has been generated automatically has 2 steps. The 1st step named "Verify that automation is enabled." has type Transact-SQL-Script:
IF (msdb.dbo.fn_syspolicy_is_automation_enabled() != 1)
BEGIN
RAISERROR(34022, 16, 1)
END
The field Run As is empty. As far as I know the SQL Server Agent Service Account is used. SQL Server Agent is running with an AD user account having sysadmin privileges.
On the other hand I cannot assign a proxy to subsystem T-SQL.
The second step named "Evaluate policies." has type PowerShell and is executed as SQL Server Agent Service Account.
What the heck is the problem here? What have I missed?
Thanks a lot in advance!
The original owner of the Database has left the company, so I want to change the owner to myself, however, it failed.
When I tried through SSMS: Database properties->Files->Owner, it give the error message like:
Set owner failed for Database XYZ.
An exception occurred while executing a Transact-SQL statement or batch.
Lock request time out period exceeded. (Microsoft SQL Server, Error: 1222)
And when I tried through script with the query:
ALTER AUTHORIZATION ON DATABASE::XYZ TO [MyUserName]
The query seems blocked and run forever without success.
Can anybody give some help?
Queries using dbo-owned objects will acquire a schema stability lock on the existing database owner principal. The ALTER AUTHORIZATION will need a schema modification lock on the same principal, and are thus blocked due to the incompatible lock. You can query sys.dm_tran_locks to identify the blocking sessions.
I currently have an issue whereby I cannot reference a table in a linked database within a stored procedure. I get the error message:
ORA-00942: table or view does not exist
Here are the steps I took on the host machine (running oracle 10g) to set up the database link to the remote database (running oracle 11g). The steps are accurate, but some some names have been changed, though they have been kept consistent.
Update tnsnames.ora, adding a new entry:
REMOTE_DB =
(DESCRIPTION =
(ADDRESS = (PROTOCOL = TCP)
(HOST = 10.10.10.10)
(QUEUESIZE = 20)
(PORT = 1521)
)
(CONNECT_DATA =
(SERVICE_NAME = remote_service)
)
)
Create database link, as the user who will later be creating and executing the stored procedure:
create database link remote_link
connect to "remote_user"
identified by "remote_pass"
using 'REMOTE_DB';
Prove database link is working by selecting from it:
select id from remote_table#remote_link;
id
--------------------------------------------------------------------------------
8ac6eb9b-fcc1-4574-8604-c9fd4412b917
c9e7ee51-2314-4002-a684-7817b181267b
cc395a81-56dd-4d68-9bba-fa926dad4fc7
d6b450e0-3f36-411a-ba14-2acc18b9c008
Create stored procedure that depends on working database link:
create or replace
PROCEDURE test_remote_db_link
AS
v_id varchar(50);
BEGIN
select id into v_id from remote_table#remote_link where id = 'c9e7ee51-2314-4002-a684-7817b181267b';
dbms_output.put_line('v_id : ' || v_id);
END test_remote_db_link;
Explode own head after staring at the following error message for over an entire working day:
Error(10,27): PL/SQL: ORA-00942: table or view does not exist
I have tried many things to try to sort this issue out, including:
When creating the database link, not using quotes around the username and password. Link creates fine, but selecting from it gives me this error:
ERROR at line 1:
ORA-01017: invalid username/password; logon denied
ORA-02063: preceding line from TWS_LINK
Tried various combinations of username and password in upper/lowercase. Received same error as 1.
Tried single quotes instead of double quotes around username and password. Recieved this error:
ERROR at line 1:
ORA-00987: missing or invalid username(s)
Proved I have full access to the remote db by connecting into it with sqlplus:
[oracle]$ sqlplus remote_user/remote_pass#REMOTE_DB
SQL*Plus: Release 10.2.0.1.0 - Production on Thu Oct 20 22:23:12 2011
Copyright (c) 1982, 2005, Oracle. All rights reserved.
Connected to:
Oracle Database 11g Enterprise Edition Release 11.2.0.2.0 - 64bit Production
With the Partitioning, OLAP, Data Mining and Real Application Testing options
SQL>
I'm not sure what to do next. The possible next step is to start looking at issues on the remote database, and perhaps see if other databases can connect to it. Another would be to look at incompatibilities going from host 10g to remote 11g.
OK so I was able to get this working, of sorts.
It turns out that when creating the database link, the double quotes around the username and password fields were causing the issue. To summarise:
If they were present, and the link created as so:
create database link remote_link
connect to "remote_user"
identified by "remote_pass"
using 'REMOTE_DB';
The remote database could be queried via sql
The stored procedure could not be compiled, recieving the ORA-942 error
As the procedure could not be compiled, it could not be executed
When the double quotes are not present:
create database link remote_link
connect to remote_user
identified by remote_pass
using 'REMOTE_DB';
The remote database could not be queried via sql, recieving an invalid password error (detailed in the question)
The stored procedure could be compiled with no errors.
The stored procedure executes as expected, retrieving data from across the database link, and displaying it.
So, even though the remote database cannot be querued via sql, recieving an invalid password error, the procedure that uses this same connection information compiles and executes normally.
I'm sure you'll agree, this is a curious state of events, and I genuinely stumbled across making it work in my scenario. I'm not quite sure I would call it a solution, as there are plenty of unanswered questions.
Hopefully if someone comes here via google, they'll find this answer useful, and at least get their code running.
GC.
I faced the same issue on 11gR2, and I'm thankful to this forum for helping me find the problem. The way to make the db link work in both SQL and procedure is to follow the below syntax (enclose only the password within double quotes).
create database link remote_link
connect to remote_user
identified by "remote_pass"
using 'REMOTE_DB';
I think I see a problem here. Is the user who is executing the stored procedure the same user who created the stored procedure?
You said, "Create database link, as the user who will later be executing the stored procedure".
If the user creating the database link is different from the user creating the stored procedure, that may be your problem.
Try creating the stored procedure and database link as the same user, or creating a public database link.
Then, since Oracle default is definer rights, you can have anyone execute the stored procedure (assuming they have been granted execute privilege on the procedure).