Suppose, I have a database named testdb
in test server.
Also I 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.
来源:https://stackoverflow.com/questions/720339/how-to-select-data-of-a-table-from-another-database-in-sql-server