Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 244
user82431 Avatar asked Apr 06 '09 05:04

user82431


People also ask

How can I access data from another database in SQL?

SELECT statements An SQL SELECT statement retrieves records from a database table according to clauses (for example, FROM and WHERE ) that specify criteria. The syntax is: SELECT column1, column2 FROM table1, table2 WHERE column2='value';

How do I select data from one table to another in SQL?

The INSERT INTO SELECT statement copies data from one table and inserts it into another table. The INSERT INTO SELECT statement requires that the data types in source and target tables match. Note: The existing records in the target table are unaffected.


2 Answers

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] 
like image 75
Matthew Farwell Avatar answered Sep 24 '22 17:09

Matthew Farwell


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

like image 36
Arthur Ronald Avatar answered Sep 24 '22 17:09

Arthur Ronald