Sunday, July 9, 2023

SQL Server - How to get data from multiple linked server

We can use a stored procedure/T-SQL statements having linked server & DB name as variables to get the data dynamically from different servers. Based on your input server name & DB name. query will connect to the particular server and database.

Below is the sample code:
CREATE PROC GetReportfromDifferentServer (
	@LinkedServerNVARCHAR(100)
	,@DB NVARCHAR(100)
	)
AS
DECLARE@SQL NVARCHAR(MAX) SET@SQL = 'SELECT * FROM  [' + @LinkedServer + '].' + @DB + '.DBO.CITY'

EXEC (@SQL)
	---Execute the SP
	EXECGetReportfromDifferentServer 'MyServer'
	,'MyDB'

No comments:

Post a Comment