10

If I want to run this sort of query in SQL Server, how can I do the same query from one server I am connected to to another?

I tried adding "[ServerName1]." before "[DatabaseName1].[dbo]..." and "[ServerName2]." before "[DatabaseName2].[dbo]..." but that didn't seem to work.

INSERT INTO [DatabaseName1].[dbo].[TableName]
           ([FieldName])
     SELECT [FieldName] FROM [DatabaseName2].[dbo].[TableName]

Is this possible?

OMG Ponies
  • 325,700
  • 82
  • 523
  • 502
sooprise
  • 22,657
  • 67
  • 188
  • 276

4 Answers4

14

Yes you would use the server-name before the whole rest of object-name like:

myserver.mydatabase.dbo.mytable

However you first have to set up linked servers. Look up linked servers in BOL.

Sid M
  • 4,354
  • 4
  • 30
  • 50
HLGEM
  • 94,695
  • 15
  • 113
  • 186
8

If you have adhoc distributed queries enabled you can use OPENDATASOURCE. Setting up a linked server is another option. Not sure of the pros and cons of each approach.

INSERT INTO [DatabaseName1].[dbo].[TableName]
SELECT FieldName
FROM OPENDATASOURCE('SQLNCLI',
    'Data Source=Server\InstanceName;Integrated Security=SSPI')
    .DatabaseName2.dbo.TableName
Martin Smith
  • 438,706
  • 87
  • 741
  • 845
  • FYI this feature has to be enabled: http://stackoverflow.com/questions/14544221/how-to-enable-ad-hoc-distributed-queries – VoteCoffee Jun 01 '15 at 15:37
2

The best way to do this would be to create a "linked server" between the two. You will need appropriate permissions to do this.

Then it's just a matter of accessing the databases using your linkedserver name.

Ex: [linkedserver].databasename.dbo.tablename

To create a linkedserver, go to server objects->right click on linked servers->click on 'new linked server'.

SoftwareGeek
  • 15,234
  • 19
  • 61
  • 78
0

In SSMS, Go to Query -> 'SQLCMD Mode'

DECLARE @VERSION VARCHAR(1000)
:CONNECT Soruce_Server_Name
SELECT @@VERSION AS [SQL_VERSION]
INTO 
:CONNECT Destination_Server_Name
[MSSQLTips].[dbo].[TEST]

Now on the Destination Server, execute your select command to check your output. For E.g.

SELECT * FROM [CloverInfotech_DB].[dbo].[TEST]