How to check if database exist on Remote Server th

2019-02-21 01:44发布

问题:

I have a table as following in SQL Server 2012.

|---------------------|------------------|------------------|
|      ClientName     |     servername   |Databasename      |
|---------------------|------------------|------------------|
|          c1         |         s1       |         b1       |
|          c2         |         s2       |         b2       |
|          c3         |         s4       |         b4       |
|          c4         |         s5       |         b6       |
|---------------------|------------------|------------------|

Is there a way to return only rows for which database exists on the server names mentioned in the table?

I searched in forums for the answer but couldn't get one. I am aware that there exists a query as mentioned here which checks whether database on that server exists or not. But in my case, I want it to be part of where clause.

Also, please consider that, this table is in server 1 but the servers in table can be different from each other.

回答1:

So, I assume you already have all your server linked and you used an account, which can read the schema. Than script will be something like this:

SELECT TOP 0 * INTO #tbl_Server_DBs
FROM tbl_Server_DBs

DECLARE ServerDBs CURSOR LOCAL STATIC FORWARD_ONLY 
FOR SELECT ClientName, servername, Databasename FROM tbl_Server_DBs

DECLARE @ClientName NVARCHAR(128), @servername NVARCHAR(128), @Databasename NVARCHAR(128);
DECLARE @s NVARCHAR(4000)

OPEN ServerDBs
FETCH NEXT FROM ServerDBs 
INTO @ClientName, @servername, @Databasename

WHILE (@@fetch_status <> -1)
BEGIN
    SET @s = N'SELECT ''' + @ClientName + N''', ''' + @servername + N''', name 
        FROM [' + @servername + N'].sys.databases
        WHERE name = ''' + @Databasename + N''';';

    PRINT @s
    INSERT INTO #tbl_Server_DBs (ClientName, servername, Databasename)
    EXEC(@s);

    FETCH NEXT FROM ServerDBs 
    INTO @ClientName, @servername, @Databasename
END

CLOSE ServerDBs
DEALLOCATE ServerDBs

SELECT * FROM #tbl_Server_DBs;


回答2:

Is there a way to return only rows for which database exists on the server names mentioned in the table?

I want it to be part of where clause.

If I understand your question correctly, you can use where exists

e.g. (you need to have server1 as linked server from the server that you are running the query from)

select * from 
schema.yourTable
where exists (select 1 from Server1.dbname.schemaName.yourServerList
                 where DatabaseName = 'b1')