Failed scheduling a task involving linked servers with SQL Server Agent - linked-server

How can I make a scheduled task work? I want to schedule a task that runs a query nightly. The query parses correctly and essentially grabs data from the SQL Server 2005 database on server2 and inserts the data into a table in a database on server1. The query and the task run on server1.
I am able to execute the query in Microsoft SQL Server Management Studio on server1. Using SQL Server Agent, I am able to create and schedule a job to execute the query but the job fails with the following error: Executed as user NT AUTHORITY\SYSTEM. Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON' [SQLSTATE 28000] [Error 18456]. IT at my company speculates that I need to be added to the interactive logon list for server2, which is part of the policy.
I have Admin privileges on both server1 and server2, though the latter should not be necessary I think. Both server1 and server2 use Windows authentication, which I gather is set up upon installation of SQL Server.
Here is what I did. First I added server2 to sys.sysservers on server1 with the following command:
EXEC sp_addlinkedserver #server='server2'
Then I created a mapping between logins on server1 and server2 with: EXEC sp_addlinkedsrvlogin #rmtsrvname = 'server2', #useself = 'true'
That allowed me to to execute the query in Microsoft SQL Server Management Studio on server1. It worked. What I found to be curious was that the following didn’t work although "Command(s) completed successfully":
EXEC sp_addlinkedsrvlogin #rmtsrvname = 'server2', #useself = 'false', #locallogin = 'MYDOMAIN\myname', #rmtuser = 'myname', #rmtpassword = '*****'
(Note that real password is unencrypted because of Windows authentication.).
I got the error
Msg 18456, Level 14, State 1, Line 1
Login failed for user 'myname'.
A value of #useself = TRUE specifies that logins use their own credentials to connect to rmtsrvname, with the rmtuser and rmtpassword arguments being ignored. FALSE specifies that the rmtuser and rmtpassword arguments are used to connect to rmtsrvname for the specified locallogin. I would have expected both to work since what I specified for rmtuser and rmtpassword are exactly what I use to log in to the remote server directly.

The job always executes as the user specified in the Sql Server Agent service. If your service is running as LocalSystem, then you need to change your add linked server login to
EXEC sp_addlinkedsrvlogin #rmtsrvname = 'server2', #useself = 'false', #locallogin = 'NT AUTHORITY\SYSTEM', #rmtuser = 'myname', #rmtpassword = '*****'
If not localsystem, then specify whatever login used in the agent
Look at this discussion for more info http://www.sqlservercentral.com/Forums/Topic1003064-146-1.aspx#bm1003182

Related

SQL works in R studio but not in R-Serivces

This code works perfectly in R-Studio but there is no way to make it work in MS Management studio. It keeps on saying that:
[Microsoft][ODBC SQL Server Driver][SQL Server]Login failed for user 'myserver\LOCAL01'.
That is not my user give it is a trusted connection. Can someone help me understand it?
ALTER PROCEDURE [dbo].[TESTIM] AS
BEGIN
SET LANGUAGE ENGLISH
CHECKPOINT 
DBCC DROPCLEANBUFFERS
EXEC sp_execute_external_script
#language = N'R'
, #script = N'
con <- "Server=myserver\\LOCAL;Database=mydb;Trusted_Connection=true";
sql <- RxInSqlServer(connectionString = con, shareDir = "c:\\TMP");
local <- RxLocalSeq(sql);
rxSetComputeContext(local)
ff <- RxSqlServerData(sqlQuery = "select top 1 * from mytable", connectionString = con);
t = rxImport(ff);
OutputDataSet <- data.frame(SUCCESS = TRUE);
'
WITH RESULT SETS (([SUCCESS] BIT))
END
So, when you execute sp_execute_external_script it executes under one of 20 Windows user accounts (worker accounts) that has been created during installation of SQL Server R Services. These accounts are created for the purpose of running tasks under a security token belonging to the SQL Server Trusted Launchpad service.
This works very well, but if you need to create a SQL connection inside your R script (as in your case) and you use trusted connection (Windows Authentication), you are executing under the user account mentioned above ('myserver\LOCAL01' in your case), and that account need to be given permission to log in to the SQL Server instance on your behalf.
To do this:
In SQL Server Management Studio, in Object Explorer, expand Security, right-click Logins, and select New Login.
In the Login - New dialog box, click Search.
Click Object Types and select Groups. Deselect everything else.
In Enter the object name to select, type SQLRUserGroup and click Check Names.
The name of the local group associated with the instance's Launchpad service should resolve to something like instancename\SQLRUserGroup. Click OK.
By default, the login is assigned to the public role and has permission to connect to the database engine.
Click OK.
That should do it (the above steps are copied from here.
If you want to read more about the user accounts you can have a look at my blog-post "Microsoft SQL Server R Services - Internals III".
Hope this helps!
Niels

MSDTC between Windows 7 (32bit) and Windows Server 2003

I am currently attempting to create a test environment for a website which is using a mixture of classic ASP and ASP.NET. (The original machines are running old versions of Windows Server, so the configuration is not to easy to mimic)
Unfortunately, I am having problems interacting from Windows 7 to the Server 2003.
The error I am getting from my test application (which simply fires a stored procedure) is as follows:
New transaction cannot enlist in the specified transaction coordinator.
After reading various articles online, I believe I have set-up the COM+ side of things on the Windows 7 machine correctly. If I change my connection string to target the old server, it succeeds.
I then ran MSDTC Simulation V1.9 and the error I recieved was as follows:
DTCping log file: C:\Users\whelans\Desktop\dtping\[servername].log
RPC server is ready
Please Start Partner DTCping before pinging
++++++++++++Validating Remote Computer Name++++++++++++
Please refer to following log file for details:
C:\Users\whelans\Desktop\dtping\[servername].log
Invoking RPC method on [servername]
Problem:fail to invoke remote RPC method
Error(0x6D9) at dtcping.cpp #303
-->RPC pinging exception
-->1753(There are no more endpoints available from the endpoint mapper.)
RPC test failed
I then tried changing my connection string password and it fails due to invalid login, so I believe the COM is reaching the server's database. The user also has full permissions on the database.
I notice in the COM+ Window, that the component in use is spinning as if communicating with the server, however, it seems the server is rejection the connection.
Any ideas?
EDIT: I have now also ran DTCTester, as i read that DTCPing will always fail on Windows 7, here was the result:
C:\Users\whelans\Desktop\dtping>dtctester.exe TestDatabase username password
Executed: dtctester.exe
DSN: TestDatabase
User Name: username
Password: password
tablename= #dtc9033
Creating Temp Table for Testing: #dtc9033
Warning: No Columns in Result Set From Executing: 'create table #dtc9033 (ival i
nt)'
Initializing DTC
Beginning DTC Transaction
Enlisting Connection in Transaction
Executing SQL Statement in DTC Transaction
Inserting into Temp...insert into #dtc9033 values (1)
Warning: No Columns in Result Set From Executing: 'insert into #dtc9033 values (
1) '
Verifying Insert into Temp...select * from #dtc9033 (should be 1): 1
Press enter to commit transaction.
Commiting DTC Transaction
Releasing DTC Interface Pointers
Successfully Released pTransaction Pointer.
Disconnecting from Database and Cleaning up Handles

dynamics AX batch job through ODBC

I have problems with an ODBC connection used in a batch job: when executed, I have the following error message :
"The ODBC operation failed.Unable to connect to database
Invalid connection String attribute Trusted_Connection
Unabe to create object 'OdbcConnection' "
I try to connect to an Access database, I use the following code:
LoginProperty loginProperty;
OdbcConnection odbcConnection;
;
loginProperty = new LoginProperty();
loginProperty.setDSN("MyDSN");
loginProperty.setDatabase("MyDatabase");
odbcConnection = new OdbcConnection(loginProperty);
when debugging, it crashes on odbcConnection = new OdbcConnection(loginProperty). I tested the same code in a job in local client execution, there was no problem and it worked fine(without defining login password in code or DSN). My DSN seems to be OK on AOS, I'm using AX 2009 without SP1, I saw some examples where there was login/password defined in loginProperty object , the setUserName() and setPassword() methods are not available in my AX version loginProperty object. My class is executed on server-side (as any batch job).
Is there some particular setup to do to connect to ODBC datasource through batch job?
any ideas or suggestions?
thanks for your help
Edit:AOS is running on Windows server 2003 32 bits, ODBC tested on it, works fine but doesn't work in AX through batch job
Most likely you will need a 32-bit DSN connection for your AX. I would create both versions on the AOS server.
Look here for details.
It may be caused due to permisions. "trusted connection" refers to the fact that you connect to the database through the user logged to the current session. When you run a Job from the AX client, this is executed with the user that runs the current AX client (the one logged to the active session); When code is executed from server in a batch job, code is executed through the user that runs the AOS windows service.
Has this user permissions to read/write/access the access file and directory?
If you are on a 64 bit machine use C:\Windows\SysWOW64\odbca32.exe to create the datasource.
Check under which ID the AOS runs, log on with that ID and make sure you can 'see' the data source.
Also make sure that the AOS account has access to the directory/files (if using file-based odbc)

How to check if SQL Server Agent is running

I am using SQL Server 2008 r2. I want to find a way to verify if SQL Server Agent is running. I am suspicious that the Agent isn't running, but I don't know how to check.
In Management Studio, you can check if SQL Server Agent is running by looking at the SQL Server Agent node in Object Explorer. In the following screen shot, SQL Server Agent on my SQL Server 2012 instance is running (green arrow overlaid on the SQL Server Agent icon), but the agent for SQL Server 2000 is stopped (red x).
You can also check in Control Panel > Administrative Tools > Services:
Or in Program Files > Microsoft SQL Server > Configuration Tools > Configuration Manager:
Finally, you can check the state using T-SQL:
DECLARE #agent NVARCHAR(512);
SELECT #agent = COALESCE(N'SQLAgent$' + CONVERT(SYSNAME, SERVERPROPERTY('InstanceName')),
N'SQLServerAgent');
EXEC master.dbo.xp_servicecontrol 'QueryState', #agent;
The quickest, easiest, most directest way to determine if SQL Agent is running, and that can be done easily in SSMS, is a query (hence it can be automated), and isn't querying a deprecated system table (i.e. sysprocesses) or EXECing xp_servicecontrol, is a DMV that was introduced in SP1 for SQL Server 2008 R2:
sys.dm_server_services
SELECT dss.[status], dss.[status_desc]
FROM sys.dm_server_services dss
WHERE dss.[servicename] LIKE N'SQL Server Agent (%';
Returns:
status status_desc
4 Running
It just requires the VIEW SERVER STATE server permission, but you already needed that in order to see the status of it in Object Explorer (in SSMS).
AND, if you don't want to grant VIEW SERVER STATE to a particular Login because it allows for getting too much other info, then you technically don't need to grant anything at all, at least not to an actual user. See the following two resources for full details (including working examples):
What minimum permissions do I need to provide to a user so that it can check the status of SQL Server Agent Service? (similar question on DBA.StackExchange)
Safely and Easily Use High-Level Permissions Without Granting Them to Anyone: Server-level (blog post)
If the SQL Server Agent is running, a green play button will be shown in the bottom right corner of the SQL Server Agent icon within SQL Server Management Studio.
To validate the status of the SQL Server Agent for a given instance using T-SQL execute the following code snippet:
IF EXISTS ( SELECT 1
FROM master.dbo.sysprocesses
WHERE program_name = N'SQLAgent - Generic Refresher')
BEGIN
SELECT ##SERVERNAME AS 'InstanceName', 1 AS 'SQLServerAgentRunning'
END
ELSE
BEGIN
SELECT ##SERVERNAME AS 'InstanceName', 0 AS 'SQLServerAgentRunning'
END
Source = Colin Stasiuk
IF EXISTS (SELECT 1 FROM sysprocesses WHERE LEFT(program_name, 8) = 'SQLAgent')
PRINT 'Agent is running!'
ELSE
PRINT 'Agent is not connected!';
Let me know if this works else try this
IF EXISTS ( SELECT 1
FROM master.dbo.sysprocesses
WHERE program_name = N'SQLAgent - Generic Refresher')
BEGIN
SELECT ##SERVERNAME AS 'InstanceName', 1 AS 'SQLServerAgentRunning'
END
ELSE
BEGIN
SELECT ##SERVERNAME AS 'InstanceName', 0 AS 'SQLServerAgentRunning'
END
Reference : http://benchmarkitconsulting.com/colin-stasiuk/2009/07/20/check-sql-server-agent-status-on-all-sql-servers/
Automate checking if SQL Server Agent is running with this batch file.
It will start start the service if it isn't running already.
You will need to tweak the service name (SQLServerAgent) for some versions of MSSQL.
echo off
echo Test SQL Server Agent Service
for /F "tokens=3 delims=: " %%H in ('sc query "SQLServerAgent" ^| findstr "STATE"') do (
if /I "%%H" NEQ "RUNNING" (
echo service was stopped, starting service
rem put your optional errorlog or warning message here
net start "SQLServerAgent"
)
)
This is what I use in powershell
Get-Service | Where-Object -like -value '*sql*agent*' -Property 'name'
Updated in 2020 for Sql Server Developer Addition 2019
View --> Registered Servers --> Local Server Groups
This should list all local servers. If there is a Red X by the server, it's stopped. Or you can right click on it and go to Service Control. From there you can Start/Stop Restart, etc.

Session management in ASP.NET with SQL Server 2005

I am getting the following error while executing InstallSqlSate.sql file
Msg 14261, Level 16, State 1, Procedure sp_add_category, Line 32
The specified #name ('[Uncategorized (Local)]') already exists.
SQLServerAgent is not currently running so it cannot be notified of
this action.
I want details about what is that error and how to fix it?
InstallState.sql is not intended to be run directly. Use aspnet_regsql.exe instead.
I had the same issue in SQL2000. Might work for 2005.
If you receive this error message, first make sure that the SQL Server
Agent service is running. To do this, follow these steps:
Click Start, click Run, type Services.msc, and then
click OK.
In the Services window, locate the SQL Server Agent
service.
Make sure that the value of the Status column of the SQL
Server Agent service is Running.
If the SQL Server Agent service is running, this problem occurs
because the SQL Server Agent service cannot interpret the dot mark (.)
that represents the local computer in the ObjectName registry entry
under the following registry subkey. For a default instance, the
registry subkey is as follows:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\MSSQLSERVER\ For
a named instance, the registry subkey is as follows:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\MSSQL$InstanceName\
Note InstanceName is a placeholder for the instance of SQL Server.
Mine was not running, it was "disabled". If this is the case for you: Right click properties, change it from disabled to Automatic. Press OK. Then right click the SQL Server Agent service and click "Start". It should change to have the "Running" status.
from: https://support.microsoft.com/en-us/kb/911841

Resources