Query database running on another physical SQL Server - sql-server

Historically we have a product which installed two databases on the same server. There is an custom application which assumes that both databases are on the same server.
In a new version they have split the databases onto two separate servers and obviously now the custom application is giving the error:
Database 'DB_2' does not exist. Make sure that the
name is entered correctly.
Is there anything I can do in the SQL Server setup so that the application is still able to query the DB_2 database without modifying the custom application?
The query being used is structured as follows:
Use DB_2
SELECT * FROM MyUser.MyTable

You can create a linked Server, then Create a Database DB_2 add a Synonym for different objects. something like below.
use master
GO;
EXEC master.dbo.sp_addlinkedserver #server = N'RemoteServer', #srvproduct=N'SQL Server'
GO
CREATE DATABASE [DB_2];
GO
USE [DB_2]
GO
CREATE SYNONYM [MyUser].[MyTable] FOR [RemoteServer].[db].[MyUser].[MyTable]
GO

You can use Linked Servers feature. In SSMS go to Server Object/Linked Servers folder in Object Explorer. And link second server. So you can query another DB using this SELECT * FROM [Linked_Server_Name].[Database_Name].[Schema_Name].[Table_Name]

Related

multiple logins with sql server linked server

I have a database server out there - lets say the url is "the.database". It has several databases on it - db_a, db_b, db_c - that all require different users and passwords.
I can happily link to one of them like this:
exec master.dbo.sp_addlinkedserver #server='the.database' #srvproduct='SQL Server'
exec master.dbo.sp_addlinkedsrvlogin #rmtrvname='the.database' #useself='false'
#rmtuser='user_a' #rmtpassword='password_a'
select top 10 * from [the.database].db_a.dbo.some_table;
And that works great. For one of them.
However - what I want to do is connect to the server simultaneously with three different logins, and I can't figure out how to do it... in fact - what I'd really like is three different linked servers - db_a, db_b, db_c - which all actually point to the.database.... but if you use "sql server" as the product, it seems like the internal server name has to correspond to the url of the actual server? In the perfect world, I'd love to end up with being able to do:
select top 10 * from [db_a].some_table
where db_a actually means database dba schema dbo on server the.database.
So basically - is there a way to create a linked server with an internal name that doesn't match the external url? Or is there another way of solving this problem?

Query from SQL Server tables in Oracle using ODI

I have a database in Oracle and a database in SQL Server.
I want to write a query in Oracle and I need to use one of SQL Serever table in it.
Before I used database link but now I must to do this with ODI (Oracle Data Integrator).
The way I used before:
CREATE PUBLIC DATABASE LINK "DBLINK"
CONNECT TO "MatrisApp" IDENTIFIED BY VALUES ':1'
USING 'dg4msql';
INSERT
INTO everyday_deposit_temp ***/*this is a table in oracle*/***
(
"DEP_ID",
"REF_DEPOSIT_TYPE",
"REF_DEPOSIT_SUB_TYPE",
"LEDGER_CODE_SELF"
)
SELECT "DEP_ID",
"REF_DEPOSIT_TYPE",
"REF_DEPOSIT_SUB_TYPE",
"LEDGER_CODE_SELF"
FROM dbo.vw_deposit_changed#dblink
Please help me with this
The most common way to get data from MS SQL Server to Oracle through ODI is to use LKM MSSQL to ORACLE (BCP SQLLDR).
Now if you really want to use a dblink, I would try this approach:
Duplicate a Oracle IKM you want to use
In the definition tab, check the Multi-Connections checkbox and set Microsoft SQL Server for the Source Technology.
In the Options tab, add a new option DBLINK_NAME with Value type.
In the Tasks tab, find the task responsible of the insert and edit the target command to add this after the table name : #<%=odiRef.getOption("DBLINK_NAME")%>
Create a mapping using the new IKM. In the Physical tab, click on the target table and add the dblink name in the Option.

How can I join two tables from two different connections or instances in SQL Server? [duplicate]

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)

Cloning SQL Server Production DB

So I have a production DB (DB1) running on one server (SERVER1) which has views that take data from another production DB (DB2) on another server (SERVER2).
Which is the best way to clone DB1 to DEV environment SERVER1_DEV (DB1_DEV) and change the connection within the views to the corresponding DB2_DEV from the corresnponding DEV server SERVER2_DEV?
Create synonyms for remote sources and use them instead of hard-coded links to any server in your views.
Example right from msdn:
CREATE SYNONYM MyProduct
FOR AdventureWorks2012.Production.Product;
GO
SELECT ProductID, Name
FROM MyProduct
WHERE ProductID < 5;
So you'll need to recreate synonyms only - to make them look at another source.

SQL Server cross database alias

I'm trying to understand how I can use an alias to reference another database in the same instance, without having to use a hardcoded name.
The scenario is as below:
I have a data db with stores data, an audit db which keeps all changes made. for various reason, i want to keep the audit data in a separate database, not least because it can get quite large and for reporting purposes.
In the data db, I don't want to reference this by a hardcoded name but an alias so that in different environments, I don't have to change the name and various sp's to reference the new name.
for example:
mydevdata
mydevaudit
If a sp exists in mydevdata such as which calls the mydevaudit, I don't want to change the sp when I go to test where the db's may be called mytestdata and mytestaudit. Again, for various reasons, the database names can change, more to do with spaces an instances etc.
So if I had procedure in mydevdata:
proc A
begin
insert into mydevaudit.table.abc(somecol)
select 1
end
when I go to test, I don't want to be change the procedure to reference another name, (assume for sake of argument that happened)
Instead I am looking to do something like:
proc A
begin
insert into AUDITEBALIAS.table.abc(somecol)
select 1
end
I am interested in finding out how I could do something like that, and the pro's and cons.
Also, dymnamic SQL is not an option.
thanks in advance for you help.
You may be able to use synonyms
CREATE SYNONYM WholeTableAliasWithDBetc FOR TheDB.dbo.TheTable
This means all object references in the local DB are local to that DB, except for synonyms that hide the other database from you.
You can also use stored procedures in the audit DB. There is a 3rd form of EXEC that is little used where you can parametrise the stored proc name
DECLARE #module_name_var varchar(100)
SET #module_name_var = 'mydevaudit.dbo.AuditProc'
-- SET #module_name_var = 'whatever.dbo.AuditProc'
EXEC #module_name_var #p1, #p2, ...
Obviously you can change module_name_var to use whatever DB you like
I've just posted this to How to create Sql Synonym or "Alias" for Database Name? which is a workaround for the same situation:
There is a way to simulate this using a linked server. This assumes you have two SQL servers with the same set of databases one for development/test and one live.
Open SQL Server Management Studio on your development/test server
Right click Server Objects > Linked Servers
Select New Linked Server...
Select the General page
Specify alias name in Linked server field - this would normally be the name of your live server
Select SQL Native Client as the provider
Enter sql_server for Product Name
In Data Source specify the name of the development server
Add Security and Server Options to taste
Click OK
The above is for SQL Server 2005 but should be similar for 2008
Once you've done that you can write SQL like this:
SELECT * FROM liveservername.databasename.dbo.tablename
Now when your scripts are run on the development server with the linked server back to itself they will work correctly pulling data from the development server and when the exact same scripts are run on the live server they will work normally.

Resources