Q:

SQL - select from variable

I am trying to find an alternative to setting the content of a variable as a big query in which i'm dynamically replacing values.
Is it possible to do something like this?
declare @serv nvarchar(max)
set @serv = '[linkedServName].[dataBaseName]'
select top 10 * from @serv.dbo.someTable

If yes, could you please show me the correct syntax?
Thank you for your time

A:

If you want to parameterize the server and database you select from, then you have to use dynamic sql. Try this:
declare @serv nvarchar(max)
declare @qry nvarchar(max)

set @serv = '[linkedServName].[dataBaseName]'
set @qry = 'select top 10 * from ' + @serv + '.dbo.someTable'

exec(@qry)

