sp_MSforeachdb: only include results from databases with results

前端 未结 2 1191
南方客
南方客 2020-12-03 16:04

I\'m running the below stored procedure sp_MSforeachdb with a simple command. My question is how to limit the result to show only the databases that have at lea

2条回答
  •  难免孤独
    2020-12-03 16:31

    You basically need another IF to only run the select if data exists. Here's what i did to test.

    On DB1:

    create table mytesttable(a int)
    insert mytesttable values(1)
    

    On DB2:

    create table mytesttable(a int)
    

    So you want DB1 to return results, but DB2 not to. you can use the following sql:

    EXECUTE master.sys.sp_MSforeachdb 'USE [?]; 
    
    IF (EXISTS (SELECT * 
                 FROM INFORMATION_SCHEMA.TABLES 
                 WHERE TABLE_NAME = ''mytesttable''))
    BEGIN
    
    IF EXISTS (SELECT 1 FROM mytesttable) BEGIN
        SELECT ''?'' as dbname,T.A
        FROM mytesttable AS T
    END
    END
    '
    

    This only returns: db1, 1

提交回复
热议问题