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?

  • How can I use LEFT & RIGHT Functions in SQL to get last 3 characters?
  • Copy table to a different database on a different SQL Server
  • Cannot drop database because it is currently in use
  • Duplicate All single rows in database table
  • To which DBs can I connect via DB LINK, from Microsoft SQL Server 2012?
  • Count each condition within group
  • Thank you for your time

    One Solution collect form web for “SQL – select from variable”

    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'
    MS SQL Server is a Microsoft SQL Database product, include sql server standard, sql server management studio, sql server express and so on.