質問

declare @node int = 9044;

DECLARE @sqlCommand NVARCHAR(MAX) = 
(
    'SELECT * FROM [@node].[database_name].dbo.table_name'
);

DECLARE @paramList NVARCHAR(400) =
(
    '@node int'
)

exec sp_executesql @sqlCommand, @paramlist, @node;

So this is the simple query I'm attempting to run. 9044 is fine. Running that query normally works perfectly (obviously I've removed the db and table names). Not entirely sure what is wrong with it. The error I get is:

Msg 7202, Level 11, State 2, Line 1 Could not find server '@node' 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.

Any ideas on how to fix this issue or should I just write the query and use EXEC (@sql)

役に立ちましたか?

解決

As per my thinking and test it only allow parameter in query part like in where and other condition.

Try this way.

declare @node int = 9044;

DECLARE @sqlCommand NVARCHAR(MAX) = 
(
    'SELECT * FROM [@node].[database_name].dbo.table_name'
);

DECLARE @paramList NVARCHAR(400) =
(
    '@node int'
)


SET @sqlCommand  = REPLACE(@sqlCommand , '@node',@node)
exec sp_executesql @sqlCommand, @paramlist, @node;

他のヒント

You are using 3-dot notation which defines the server.db.table @nodes is looking for a server of this name ...are you looking for this server name dynamically.. the best way would be to create a linked server object or alias and refer to it this was i.e

MyServer = dev-sql-server.AdventureWorks etc 

Or you may just need to get rid of the extra [@node].

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top