Connect to another SQL Server via SQL Query? - sql

Is it possible to connect to another SQL Server using a SQL query (so that one can also run queries on that server and use the result set in current server). If not, then why ?

Yes, you can accomplish connecting to another SQL Server by using a Linked Server, or you can query through servers by using openquery:
SELECT * FROM openquery([aa-db-dev01], 'Select * from TestDB.dbo.users')
Querying a linked sql server

Microsoft SQL Server only:
Yes, it is possible. You have to configure a linked Microsoft SQL Server. Here is the info: http://msdn.microsoft.com/en-us/library/ms188279.aspx
Once you have your servers configured, your query (on server1) would look like the following:
SELECT TOP 10 * FROM server2.yourdatabase.yourschema.yourtable

It is not simply possible to connect to 2 different SQL servers simultaneously with one query if you have a query that needs to run on 2 SQL servers' databases to get a required resultset (distributed query)
Then you must have to create a "Linked Server" in your local SQL server "linked to" the 2nd SQL server (the remote SQL server)
Once the Linked Server is created in your local server you may query both servers with one query from your local server's connection.
The linked Servers can be queried directly or by using OPENQUERY.
There is a difference of performance between 'Direct Linked Server Query' and 'Linked Server OPENQUERY' as in the direct query entire data will be flown back to local server from remote server and then the local server will process the filters locally while in OPENQUERY the process will be completed on the remote server and local server will get only the filtered dataset

This works in SQL 2012.
Shows up in a grey box
Has to be run prior to the SQL to be run on the other server, else the code runs on which ever server/database the query window is connected to. Local variables like ##Servername and SERVERPROPERTY return the same results as the server connected to. Which was darn unexpected!!!!
:Connect servername
Example run from SQLTEST
SELECT CONVERT(sysname, SERVERPROPERTY('servername'));
:Connect CSQL2008
SELECT CONVERT(sysname, SERVERPROPERTY('servername'));
SELECT CONVERT(sysname, SERVERPROPERTY('servername'));
Produces:
CSQL2008
CSQL2008
CSQL2008
While
select distinct( server_name) from msdb.dbo.backupset
go
:Connect CSQL2012
select distinct( server_name) from msdb.dbo.backupset ;
go
select distinct( server_name) from msdb.dbo.backupset ;
produces:
SQLTEST
CSQL2012
CSQL2012

Related

How do you pull data from a database to another one using a linked server?

I have a local server set up on my computer with a local database. I am trying to connect to a network server with a linked server (I'm having a lot of trouble with this) and then create tables and views in the local database from the data in the network database. I'm using Microsoft SQL Server Management Studio 2012.
Try something like :
SELECT * from openquery(LINKED_SERVER_NAME,'SELECT * FROM TABLE')
If your linked server is well configured, you should be able to query the tables in the linked server using openquery.
Try this. First you link the Server then run query against the linked Server.
EXEC Sp_addlinkedserver
#server="MY-PC\SQLServer1",
#srvproduct='SQL Server'
-- from SQL Server2 you run this query
SELECT *
FROM Openquery("my-pc\sqlserver1", 'select * from Students')
Reference: Running Query against linked Server
SELECT * FROM [LINKEDSERVERNAME].[DATABASENAME].[DBO].[TABLENAME]

SQL Server: Query not linked server providing credencials. Is possible?

I tried to query another specific server many times, but i failed... I searched and i found out that the server must be linked with the other server in order to achieve what i want. Unfortunately is not in my hands to change that so my question is, if it is possible to query the other server by providing credentials.
The server i want to query has SQL Server 2005 Service Pack 4 (9.00.5000) and the server i'm working on has SQL Server 2005 Service Pack 3(9.00.4035).
Thanks in advance.
Use OPENROWSET or OPENDATASOURCE instead. Both allow you to pass credentials. This is your best option if you are unable to use a linked server.
This example works if you are using SQL Server logins.
SELECT a.*
FROM OPENROWSET('SQLNCLI', 'SERVER=<servername>;UID=<username>;PWD=<password>',
'SELECT FOO FROM FOO.BAR') AS a

How to select a table from one machine to another using sql server 2008 r2?

I have explained the scenario below:
I am having two servers:
server 1
server 2
In both the servers I have Sql Server 2008 r2.
In server 1, I have a database named "DB_Server1" and in server 2, a database named "DB_Server2".
In DB_server1 database, I have a table named "TB_Server1" and in DB_Server2, a table named "TB_Server2".
My requirement is, in DB_Server1, I'm going to write a stored procedure which selects the table "TB_Server2" from DB_Server2 which is located in the server 2.
How can I achieve the above requirement?
you can use linkserver
at first select Server1
step 1: exec sp_addlinkedserver 'Server2'
step 2: select * from [Server2].[DB_Server2].TB_Server2
You can create linked server (http://msdn.microsoft.com/library/ff772782.aspx)
Use Linked Server:
Allows you to query databases and tables on remote servers as though they are part of the local database. Very easy to setup (just call exec sp_addlinkedserver) and once defined uses nothing but plain old SQL.
Here is a simple tutorial about how to create a linked server. After creating linked server, we can query it as follows:
select * from LinkedServerName.DatabaseName.dbo.TableName
Click here for another tutorial.
Read more about Linked Servers here.

Selecting data from two different servers in SQL Server

How can I select data in the same query from two different databases that are on two different servers in SQL Server?
What you are looking for are Linked Servers. You can get to them in SSMS from the following location in the tree of the Object Explorer:
Server Objects-->Linked Servers
or you can use sp_addlinkedserver.
You only have to set up one. Once you have that, you can call a table on the other server like so:
select
*
from
LocalTable,
[OtherServerName].[OtherDB].[dbo].[OtherTable]
Note that the owner isn't always dbo, so make sure to replace it with whatever schema you use.
You can do it using Linked Server.
Typically linked servers are configured to enable the Database Engine to execute a Transact-SQL statement that includes tables in another instance of SQL Server, or another database product such as Oracle. Many types OLE DB data sources can be configured as linked servers, including Microsoft Access and Excel.
Linked servers offer the following advantages:
The ability to access data from outside of SQL Server.
The ability to issue distributed queries, updates, commands, and transactions on heterogeneous data sources across the enterprise.
The ability to address diverse data sources similarly.
Read more about Linked Servers.
Follow these steps to create a Linked Server:
Server Objects -> Linked Servers -> New Linked Server
Provide Remote Server Name.
Select Remote Server Type (SQL Server or Other).
Select Security -> Be made using this security context and provide login and password of remote server.
Click OK and you are done !!
Here is a simple tutorial for creating a linked server.
OR
You can add linked server using query.
Syntax:
sp_addlinkedserver [ #server= ] 'server' [ , [ #srvproduct= ] 'product_name' ]
[ , [ #provider= ] 'provider_name' ]
[ , [ #datasrc= ] 'data_source' ]
[ , [ #location= ] 'location' ]
[ , [ #provstr= ] 'provider_string' ]
[ , [ #catalog= ] 'catalog' ]
Read more about sp_addlinkedserver.
You have to create linked server only once. After creating linked server, we can query it as follows:
select * from LinkedServerName.DatabaseName.OwnerName.TableName
SELECT
*
FROM
[SERVER2NAME].[THEDB].[THEOWNER].[THETABLE]
You can also look at using Linked Servers. Linked servers can be other types of data sources too such as DB2 platforms. This is one method for trying to access DB2 from a SQL Server TSQL or Sproc call...
Querying across 2 different databases is a distributed query. Here is a list of some techniques plus the pros and cons:
Linked servers: Provide access to a wider variety of data sources than SQL Server replication provides
Linked servers: Connect with data sources that replication does not support or which require ad hoc access
Linked servers: Perform better than OPENDATASOURCE or OPENROWSET
OPENDATASOURCE and OPENROWSET functions:
Convenient for retrieving data from data sources on an ad hoc basis.
OPENROWSET has BULK facilities as well that may/may not require a format file which might be fiddley
OPENQUERY: Doesn't support variables
All are T-SQL solutions. Relatively easy to implement and set up
All are dependent on connection between source and destionation which might affect performance and scalability
These are all fine answers, but this one is missing and it has it's own powerful uses. Possibly it doesn't fit what the OP wanted, but the question was vague and I feel others may find their way here. Basically you can use 1 window to simultaneously run a query against multiple servers, here's how:
In SSMS open Registered Servers and create a New Server Group under Local Server Groups.
Under this group create New Server Registration for each server you wish to query. If the DB names are different ensure to set a default for each in the properties.
Now go back to the Group you created in the first step, right click and select New Query. A new query window will open and any query you run will be executed on each server in the group. The results are presented in a single data set with an extra column name indicating which server the record came from. If you use the status bar you will note the server name is replaced with multiple.
try this:
SELECT * FROM OPENROWSET('SQLNCLI', 'Server=YOUR SERVER;Trusted_Connection=yes;','SELECT * FROM Table1') AS a
UNION
SELECT * FROM OPENROWSET('SQLNCLI', 'Server=ANOTHER SERVER;Trusted_Connection=yes;','SELECT * FROM Table1') AS a
I had the same issue to connect an SQL_server 2008 to an SQL_server 2016 hosted in a remote server. Other answers didn't worked for me straightforward. I write my tweaked solution here as I think it may be useful for someone else.
An extended answer for remote IP db connections:
Step 1: link servers
EXEC sp_addlinkedserver #server='SRV_NAME',
#srvproduct=N'',
#provider=N'SQLNCLI',
#datasrc=N'aaa.bbb.ccc.ddd';
EXEC sp_addlinkedsrvlogin 'SRV_NAME', 'false', NULL, 'your_remote_db_login_user', 'your_remote_db_login_password'
...where SRV_NAME is an invented name. We will use it to refer to the remote server from our queries. aaa.bbb.ccc.ddd is the ip address of the remote server hosting your SQLserver DB.
Step 2: Run your queries
For instance:
SELECT * FROM [SRV_NAME].your_remote_db_name.dbo.your_table
...and that's it!
Syntax details: sp_addlinkedserver and sp_addlinkedsrvlogin
Server 2008:
When in SSMS connected to server1.DB1 and try:
SELECT * FROM
[server2].[DB2].[dbo].[table1]
as others noted, if it doesn't work it's because the server isn't linked.
I get the error:
Could not find server DB2 in sys.servers. Verify that the correct
server name was specified. If necessary, execute stored procedure
sp_addlinkedserver to add the server to sys.servers.
To add the server:
reference: To add server using sp_addlinkedserver
Link: [1]: To add server using sp_addlinkedserver
To see what is in your sys.servers just query it:
SELECT * FROM [sys].[servers]
Simplified solution for adding linked servers
First server
EXEC sp_addlinkedserver #server='ip,port\instancename'
Second Login
EXEC sp_addlinkedsrvlogin 'ip,port\instancename', 'false', NULL, 'remote_db_loginname', 'remote_db_pass'
Execute queries from linked to local db
INSERT INTO Tbl (Col1, Col2, Col3)
SELECT Col1, Col2, Col3
FROM [ip,port\instancename].[linkedDBName].[linkedTblSchema].[linkedTblName]
Created a Linked Server definition in one server to the other (you need SA to do this), then just reference them with 4-part naming (see BOL).
select *
from [ServerName(IP)].[DatabaseName].[dbo].[TableName]
As #Super9 told about OPENDATASOURCE using SQL Server Authentication with data provider
SQLOLEDB
. I am just posting here a code snippet for one table is in the current sever database where the code is running and another in other server '192.166.41.123'
SELECT top 2 * from dbo.tblHamdoonSoft tbl1 inner JOIN
OpenDataSource('SQLOLEDB','Data Source=192.166.41.123;User ID=sa;Password=hamdoonsoft')
.[TestDatabase].[dbo].[tblHamdoonSoft1] tbl2 on tbl1.id = tbl2.id
I know this is an old question but I use synonyms. Supposedly the query is executed within database server A, and looks for a table in a database server B that does not exist on server A. Add then a synonym on A database that calls your table from server B. Your query doesn't have to include any schemas, or different database names, just call the table name per usual and it will work.
There's no need to link servers as synonyms per say are sort of linking.
sp_addlinkedserver('servername')
so its should go like this -
select * from table1
unionall
select * from [server1].[database].[dbo].[table1]
Server Objects---> linked server ---> new linked server
In linked server write server name or IP address for other server and choose SQL Server
In Security select (be made using this security context )
Write login and password for other server
Now connected then use
Select * from [server name or ip addresses ].databasename.dbo.tblname
I hope the clarifications all mentioned above, have answered the OP's original question. I just want to add a code snippet for adding SQL Server as a linked server.
At most basic, we can simply add SQL Server as a linked server by executing sp_addlinkedserver with only one parameter #server, i.e.
-- using IP address
exec sp_addlinkedserver #server='192.168.1.11'
-- PC domain name
exec sp_addlinkedserver #server='DESKTOP-P5V8JTN'
SQL Server will automatically fill SRV_PROVIDERNAME, SRV_PRODUCT, SRV_DATASOURCE etc. with default values.
By doing this, we've to write the IP or PC domain name in the 4 part table address in the query (example below). This can be more annoying or less readable when the linked server will not have a default port or instance, the address will look similar to this 192.168.1.11,1430 or 192.168.1.11,1430\MSSQLSERVER2019.
So, to keep 4 part address short and readable, we can add an alias name for the server instead of the full address by specifying other parameters as follows-
exec sp_addlinkedserver
#server='ReadSrv1',
#srvproduct='SQL Server',
#provider='SQLNCLI',
#datasrc='192.168.1.11,1430\MSSQLSERVER2019'
But when you'll execute the query, the following error will show- You cannot specify a provider or any properties for product 'SQL Server'.
If we keep the server product property value empty '' or any other value, the query will execute successfully.
Next step, make login to the remote linked server by executing the following query-
EXEC sp_addlinkedsrvlogin #rmtsrvname = 'ReadSrv1', #useself = 'false', #locallogin = NULL, #rmtuser = 'sa', #rmtpassword = 'LinkedServerPasswordForSA'
Finally, use the linked server with 4 part address, the syntax is-
[ServerName].[DatabaseName].[Schema].[ObjectName]
Example-
SELECT TOP 100 t.* FROM ReadSrv1.AppDB.dbo.ExceptionLog t
To list existing linked servers execute:
exec sp_linkedservers
To delete a linked server execute:
exec sp_dropserver #server = 'ReadSrv1', #droplogins='droplogins' (delete login as well) OR
exec sp_dropserver #server = 'ReadSrv1', #droplogins='NULL' (keep login)

How to select data of a table from another database in SQL Server?

Suppose that I have a database which name is testdb in test server.
I also have a database named proddb in prod server.
Now I want to select data of a table of testdb database from proddb database.
How can I do that in SQL Server?
Also, I can do it using database link in oracle. But how can do that in SQL Server?
You need sp_addlinkedserver()
http://msdn.microsoft.com/en-us/library/ms190479.aspx
Example:
exec sp_addlinkedserver #server = 'test'
then
select * from [server].[database].[schema].[table]
In your example:
select * from [test].[testdb].[dbo].[table]
In SQL Server 2012 and above, you don't need to create a link. You can execute directly
SELECT * FROM [TARGET_DATABASE].dbo.[TABLE] AS _TARGET
I don't know whether previous versions of SQL Server work as well
I've used this before to setup a query against another server and db via linked server:
EXEC sp_addlinkedserver #server='PWA_ProjectServer', #srvproduct='',
#provider='SQLOLEDB', #datasrc='SERVERNAME\PWA_ProjectServer'
per the comment above:
select * from [server].[database].[schema].[table]
e.g.
select top 6 * from [PWA_ProjectServer].[PWA_ProjectServer_Reporting].[dbo].[MSP_AdminStatus]
To do a cross server query, check out the system stored procedure: sp_addlinkedserver in the help files.
Once the server is linked you can run a query against it.
Using Microsoft SQL Server Management Studio you can create Linked Server. First make connection to current (local) server, then go to Server Objects > Linked Servers > context menu > New Linked Server. In window New Linked Server you have to specify desired server name for remote server, real server name or IP address (Data Source) and credentials (Security page).
And further you can select data from linked server:
select * from [linked_server_name].[database].[schema].[table]
Try using OPENDATASOURCE
The syntax is like this:
select * from OPENDATASOURCE ('SQLNCLI', 'Data Source=192.168.6.69;Initial Catalog=AnotherDatabase;Persist Security Info=True;User ID=sa;Password=AnotherDBPassword;MultipleActiveResultSets=true;' ).HumanResources.Department.MyTable
Select * from [Database].[dbo].[TableName]
select * from [dbTest].[dbo].[Products]