简体   繁体   中英

quering remote database using sql server?

I have used sp_addlinkedserver to access the remote machines db now i am writing queries explicitly on database like,

select * from [server\\instance].database.owner.tablename

Now with this,

  1. [Server\\instance] : this has to be provided explicitly
  2. [database] : can we find databases on specified instance using query like ms_ForEachDB ?
  3. [owner] : Can we find the database owner name using query ?

If these values are found using queries do we need to use EXEC() to execute this or we can still achieve it using nice queries ?

Thanks all,

The "nice" format you mention is simply a 4 part object reference.

select * from [server\instance].database.owner.tablename

3 part

select * from database.owner.tablename

2 part

select * from owner.tablename

If you want to dynamically change any of the server, db or schema values then you have one option:

EXEC (@sqlstring)

However, if you only access stored procs remotely...

DECLARE @RemoteSP varchar(500)

SET @RemoteSP = '[server\instance].database2.schema.proc2'
EXEC @RemoteSP @p1, @p2, @p3 OUTPUT

SET @RemoteSP = '[server\instance].database1.schema.proc1'
EXEC @RemoteSP @p4, @p5, @p6 OUTPUT

However, changing the components of the object reference makes no sense arguably: if you know you're going to query a table then just call that table in that database...

you should make a query string and then run it by exec() function.

getting server name :

SELECT @@SERVERNAME

getting current db name :

SELECT DB_NAME() AS DataBaseName

You do not have to use EXEC you could use something like select * from openquery(MyLinkedServer,@sql) THough i prefer EXEC(@sql) AT MyLinkedServer

But all work

If it happens that you need to use some sort of variable in your arguments(eg collect remote's server updates since yesterday):

DECLARE @yesterday NVARCHAR(20) = '2016-09-23 08:16:20';
DECLARE @sql NVARCHAR(MAX) = N'SELECT * FROM database.targetTable AS origin
                          WHERE origin.columnWithDateTime >'''+@yesterday+''';';
PRINT @sql;
EXEC(@sql) AT linkedServer

______

Where:

database.targetTable : For some reason SSMS 2008 R2 returns error if you describe it as [database].[targetTable], and i don't know why that happens.

: Is the variable you want to insert (this case, a string containing datetime-like element) :是否要插入变量(这种情况下,包含类似datetime的元素的字符串)

: Just to verify if the quotes are correctly placed. :只是为了验证是否正确放置了引号。

: Should be a column with datetime format (eg "timestamp", or similar to the variable format. :应该是具有日期时间格式的列(例如“timestamp”,或类似于变量格式。

"OPENQUERY does not accept variables for its arguments.": See Here (MSDN: OPENQUERY (Transact-SQL)).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM