Connect to remote server in T-SQL (SQL server 2008) - sql

Does anyone have an example of a stored procedure which makes a connection to a remote server?
I have been searching the web and have so far discovered that it might can be done using sp_addlinkedserver and sp_addlinkedsrvlogin but I haven't found a good example and I don't understand the documentation that well.
UPDATE:
None of the two first replies help me out, the closest I can get is using this:
EXEC sp_addlinkedserver
#server = 'SiminnSrv',
#provider = 'SQLNCLI',
#catalog = 'devel',
#srvproduct = '',
#provstr = 'DRIVER={SQL Server};SERVER=my.serveradr.com;UID=my_user_name;PWD=my_pass_word;'
That actually makes me connect but when I query a table I get this message:
Login failed for user '(null)'. Reason: Not associated with a trusted SQL Server >connection.

Essentially you create a linked server to the other server, and then provide login credentials to be used for SQL calls to that linked server. e.g. this will connect to "MyOtherServer" using a DomainAccount for that server with the username & password 'DomainUserName', 'DomainPassword'
EXEC sp_addlinkedserver 'MyOtherServer', N'SQL Server'
EXEC sp_addlinkedsrvlogin
'MyOtherServer',
'false',
'OtherServerDomain\DomainUser',
'DomainUserName',
'DomainPassword'
More Info Here And Here

I managed to connect to MSSQL Server 2008 through a linked server using the "SQL Server Native Client 10" (SQLNCLI10), but I had to use sp_addlinkedsrvlogin instead of #provstr to provide the connection details. This is based on the example from this article:
EXEC master.dbo.sp_addlinkedserver
#server = 'MyServerConnection',
#srvproduct = '',
#datasrc = 'SERVERNAME\INSTANCENAME',
#provider = 'SQLNCLI10',
#provstr = ''
EXEC sp_addlinkedsrvlogin
#rmtsrvname = 'MyServerConnection',
#useself = 'false',
--#locallogin = 'someLocalUser' -- Use to restrict the connection to specific login
#rmtuser = 'remoteUser',
#rmtpassword = 'secret'
Querying this linked server:
SELECT *
FROM [MyServerConnection].[SomeDatabase].[dbo].[TableName]

I may be late to the party, but I found the following links worked for me:
To perform the intial link, I used
EXEC sp_addlinkedserver #server='serverLinkPseudonym',#srvproduct='',#provider='SQLOLEDB', #datasrc='192.168.1.1';
Then, as I was logging in with Windows authentication, I added the Windows user (this cured my " Not associated with a trusted SQL Server" error)
EXEC sp_addlinkedsrvlogin 'serverLinkPseudonym', 'false', 'MACHINENAME\windowsLogin', 'lnkSrvLogin', 'lnkSrvPswd';
I also found that if I was going to run SQL Server Agent jobs that made calls to the LinkedServer, I had to add the following:
EXEC sp_addlinkedsrvlogin 'serverLinkPseudonym', 'false', 'NT AUTHORITY\SYSTEM', 'lnkSrvLogin', 'lnkSrvPswd';
For the sake of clarity:
"192.168.1.1" is the IP of the server to be linked to.
"lnkSrvLogin" is a login on the server to be linked to, that has access to the database(s) that you need to access.
"lnkSrvPswd" is the password of that account.
If you are connecting to the linked server, using an account from the existing server, then you just use that account name in the sp_addlinkedsrvlogin command. eg:
EXEC sp_addlinkedsrvlogin 'serverLinkPseudonym', 'false', 'thisServerLogin', 'lnkSrvLogin', 'lnkSrvPswd';
Then test it:
SELECT * FROM [serverLinkPseudonym].[DBName].[dbo].[TableName]

IF you want to be able to query another server, you will need to create a linked server.
This page has a pretty thorough explination of how the sp works.
http://doc.ddart.net/mssql/sql70/sp_adda_17.htm
if you want to link to antoher sql server, just execute this:
sp_addlinkedserver #server='ServerName', #srvproduct='SQL Server'
#server is the name of the server you want to add. #srcproduct is the type of server it is. there might be some other things you'll have to do to hook up 2008 to 2005, but 2008 should work like this.

Related

sp_addlinkedsrvlogin / revert

I am a sysadmin on the two SQL server machines (obviously not a very good one). I linked the servers by using sp_addlinkedserver. I was successful, and my query ran fine as T-SQL and a stored procedure. I tried to setup my stored procedure to run as a SQL Server Agent job. It was here that it was failing. I tried making a user on both servers the owner, but it was still failing. I did some reading and I wanted to add a mapped user. I ran the following command, not thinking it through, and now my user is messed up. I keep getting permission issues.
EXEC sp_addlinkedsrvlogin
#rmtsrvname = 'servername',
#useself = 'true',
#locallogin = 'null
How do I revert this back? I tried dropping the linked server and logins... my user doesn't have that permission anymore. I can do that as Sa. I can't add the linked server with my user anymore, gotta do that with sa.
Basically, how do I restore my permissions? I'm still sysadmin in both SQL instances.
thanks
So I did figure it out myself. I logged in as SA to perform the following command.
EXEC sp_droplinkedsrvlogin
#rmtsrvname = 'remoteserver',
#locallogin = 'domain\user'
this did the trick, but I did have to close out of all active connections as the domain user, restart SSMS in order for me permissions to get returned.

sp_addlinkedsrvlogin doesn't work but sp_addlinkedserver does?

I can add a link server with EXEC sp_addlinkedserver, (With no credentials) successfully, however, I need to provide a username and password to a server if the Windows Authentication doesn't work.
So I have tried using
EXEC sp_addlinkedsrvlogin #rmtsrvname='ServerName',
#useself=N'False',
#locallogin=NULL,
#rmtuser='sa',
#rmtpassword='Password'
Which this error appears
Msg 15015, Level 16, State 1, Procedure sp_addlinkedsrvlogin, Line 49
The server 'ServerName' does not exist. Use sp_helpserver to show
available servers
.
I dont understand as looking online, I have understood the two prodcecures to be the same, but sp_addlinkedsrvlogin takes a username and password and then creates the link server. I guess I have this wrong? So if I have, is there a SQL Server Procedure that will do what I want?
Cheers
I have understood the two prodcecures to be the same
Incorrect. sp_addlinkedsrvlogin is documented as:
Creates or updates a mapping between a login on the local instance of SQL Server and a security account on a remote server.
Nowhere is said that it creates a linked server. In fact the very first argument is properly documented as:
#rmtsrvname Is the name of a linked server that the login mapping applies to
You first create the linked server via sp_addlinkedserver, you then add the linked server login via sp_addlinkedsrvlogin.

SQL Server 2012 linked server Application Intent

I need to create a linked server against a SQL Server 2012 Availability Group and I want to have all requests routed to the read only replica. However, I have been unable to determine how I can specify the ReadOnly Application Intent in order to ensure that the request is routed to the correct replica.
Has anyone sucessfully configured a linked server in this manner?
I have tried both methods and the below (from the Microsoft tech site) works
EXEC sp_addlinkedserver
#server = N'linked_svr',
#srvproduct=N'SqlServer',
#provider=N'SQLNCLI11',
#datasrc=N'AG_Listener_Name',
#provstr=N'ApplicationIntent=ReadOnly',
#catalog=N'MY_DB_NAME';
When testing a Linked Server connection to the database I found that I was still hitting the primary database even when specifying ApplicationIntent=ReadOnly in the connection parameters.
After further investigations I found that the root cause for this was because the default database associated with that login was set to "master". This can be tested by running the following query:
sp_helplogins
To avoid this issue I now use the following connection parameters to ensure I am connecting to the database replica:
ApplicationIntent=ReadOnly;Database=database-db
Also, when connecting to a database via a linked server, please be sure to use the following query format:
SELECT * FROM [server].[database].[scheme].[table]
I Don't have an AlwaysOn availability group to test this on, but you can specify a connection string when setting up a linked server via sp_addlinkedserver.
SQL Server 2012 accepts the following and successfully creates a linked server that works, whether it honours the ApplicationIntent property you will have to test, but it should do as it is set to use the native client as a provider:
sp_addlinkedserver
#srvproduct = 'DB', --Don't use 'SQL Server' otherwise it won't let you set any properties
#server = 'LINKED-SERVER-NAME',
#provider = 'SQLNCLI',
#provstr = 'Data Source=SERVER\INSTANCE;Initial Catalog = Database;ApplicationIntent=ReadOnly'
https://learn.microsoft.com/en-us/windows-server/networking/core-network-guide/cncg/server-certs/create-an-alias-cname-record-in-dns-for-web1
I have used CNAME for READONLY NODE.
sql AO or windows cluster its very useful for readonly servers.
EX: Your second node server name is SERVERB, you redirect it to alias name as below.
SERVERB ----- >SERVERB.corp.contoso.com.
Then from the SSMS check if you can connect, or ping the alias name from the command promt screen if it works.
ping SERVERB.corp.contoso.com

Login Failed for linked server

How to create a linked server...?
1st Server name is ABC.DATABASE1
2nd server name is EFG.DATABASE2
EFG database username is sa password is sa
I want to retrive the data's from 2nd server thourgh 1st server
In the 1st server, i exectue the store procedure like this....
exec sp_linkedserver 'EFG'
Executed successfully,
When i tried to retrive the data, it is showing error as "login failed for user sa, Reason: Not associated with trusted sql server connection"
How to solve this problem...
Need help
In Microsoft SQL Server Management Studio check the login configuration of your linked servers properties on the *Security" tab and create a mapped remote login for your local sa account or configure an alternative login for all connections.
To create a linked server with a login mapping by executing sp_linkedserver, try
sp_addlinkedsrvlogin #rmtsrvname = N'EFG', #locallogin = N'sa', #useself = N'False',
#rmtuser = N'your_remote_user', #rmtpassword = N'remotepassword'
To create a linked server with an alternative login, try
sp_addlinkedsrvlogin #rmtsrvname = N'EFG', #locallogin = NULL , #useself = N'False',
#rmtuser = N'your_remote_user', #rmtpassword = N'remotepassword'

Stored Procedure: Linked server login failure

I'm getting "Msg 18456, Level 14, State 1, Line 1
Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON'." from when trying to execute the code below. I've change all of the critical information, but you should get the idea.
Are some of my parameter incorrect? The local sql admin username is correct and the remote username and password is correct, but it still keeps telling me that the login failed. Any ideas?
Overall, are there other changes I need to make? Can I insert data this way?
Both DBs are sql server 2005. One is local, one is offsite and accessible via a secure vpn tunnel. I have no trouble acessing the offsite DB using SSMS using the username and password i've been provided(those i've been using in my SP).
-- establish the linked server and login.
EXEC sp_addlinkedserver #server=SERVER1,#srvproduct='',#provider='SQLNCLI', #datasrc='SERVER IP ADDRESS'
EXEC sp_addlinkedsrvlogin SERVER1, 'false', 'LOCAL SQL ADMIN USERNAME', 'REMOTE USERNAME', 'REMOTE PASSWORD'
insert into [SERVER1].DATABASE.dbo.INSERTTABLE(....) select fields from localtable
-- drop the linked server and login
EXEC Sp_DropServer SERVER1, 'droplogins'
I suspect the target server is set to "Windows Authentication" only.
When you try and connect as a SQL login (specified in sp_addlinkedsrvlogin), it tries to interpret the credentials as windows and fails
This error normally occurs when #useself = 'true' for sp_addlinkedsrvlogin and the calling SQL Server is not configured for delegation. The server (not SQL server) can not pass through the Windows credentials.
1) use named parameters for sp_addlinkedsrvlogin for explicitness.
2) use "go" between statements (don't execute the above as a single batch).
3) set "local sql admin username" to null - to rule that out
4) just to note, it appears that remote username/password (if specified) need to be sql-server logins, not NT Network Logins
Start with those...!
Unsure of the exact cause folks. I just moved on a created a Linked Server through the SSMS GUI.