1

I am running this from SQL Server 2008 R2.

Is it possible to use a variable name when writing a query to query from sys.servers?

DECLARE @hostname varchar(20)
SET @hostname = '192.168.110.101'
SELECT TOP(10) * FROM [@hostname].databasename.dbo.tablename

return "Could not find server '@hostname' in sys.servers. Verify that the correct server name was specified. If necessary, execute the stored procedure sp_addlinkedserver to add the server to sys.servers.".

It appears that it is trying literally use @hostname and not what the variable is actually set to. I have also tried removing the brackets and this do not work either. Any ideas?

4

1 回答 1

1
DECLARE @SQL as varchar(max)
SET @SQL = 'SELECT TOP 10 * FROM '
DECLARE @hostname varchar(20)
SET @hostname = '192.168.110.101'
SET @SQL = SQL + @hostname + '.databasename.dbo.tablename'

EXEC (@SQL)
于 2013-06-17T23:46:06.917 回答