1

I need to find all databases on a linked server having the same value inside a certain table like the database on the source server which calls the query.

I've build a query which works fine as long as all databases on the linked server have this table. Otherwise it fails telling me:

The OLE DB provider "SQLNCLI11" for linked server "MyServer" does not contain the table ""DbName"."dbo"."TableName"". The table either does not exist or the current user does not have permissions on that table.

This is my code:

CREATE TABLE #x(DB SYSNAME, name varchar(255));

DECLARE @guid uniqueidentifier;
SET @guid = (SELECT guid FROM TableName);

DECLARE @sql NVARCHAR(MAX);
SET @sql = N'';

SELECT @sql = @sql + 'IF EXISTS (SELECT 1 FROM [LinkedServer].'
+ QUOTENAME(name) + '.sys.tables WHERE name = ''TableName'')
INSERT #x SELECT ''' + name + ''', name
    FROM [LinkedServer].' + QUOTENAME(name) + '.dbo.TableName
    WHERE guid = ''' + CONVERT(NVARCHAR(36), @guid) + ''';'
FROM [LinkedServer].master.sys.databases;

EXEC sp_executesql @sql;

SELECT * FROM #x;
DROP TABLE #x;

Is there a way to solve this?

1 Answer 1

1

since you don't know if the table exists in specific database at compile time, you have to use dynamic sql:

SELECT @sql += '
  IF EXISTS (SELECT 1 FROM [LinkedServer].' + QUOTENAME(name) + '.sys.tables WHERE name = ''TableName'')
exec (''INSERT #x SELECT ''''' + name + ''''', name
    FROM [LinkedServer].' + QUOTENAME(name) + '.dbo.TableName
    WHERE guid = ''''' + CONVERT(NVARCHAR(36), @guid) + ''''''');'
FROM [LinkedServer].master.sys.databases;
where database_id > 4

so you have dynamic inside of dynamic.

Sign up to request clarification or add additional context in comments.

3 Comments

What happens if the linked server doesn't have a master DB (i.e. isn't a SQL Server)?
This is no problem in my case - it's always a SQL Server with a master DB. But @Ivan, did you test your solution? I tried to adapt this but I'm getting an error: "Incorrect syntax near 'TableName'."
@vso, check quotes. print @sql for debug.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.