0

Is there a way to combine records into one table across databases (and on different servers) when using SQL CMD MODE in SSMS?

:Connect Database1
select firstname,lastname from table1
GO
:Connect Database2
select firstname,lastname from table1
GO
:Connect Database3
select firstname,lastname from table1
GO

How can I put all the results in one table?

halfer
  • 19,824
  • 17
  • 99
  • 186
Rod
  • 14,529
  • 31
  • 118
  • 230

1 Answers1

1

Yes you could use variables to hold the servers, union the results and use select into, it would look something like:

:setvar serv1 "server1"
:setvar serv2 "server2"

:Connect $(serv1)
select column into #Result
from database.schema.table
union all
select column from $(serv2).database.schema.table

select * from #Result /* Temp table on server1 */
Stu
  • 30,392
  • 6
  • 14
  • 33