Sqlserver
 sql >> Base de données >  >> RDS >> Sqlserver

sp_MSforeachdb :n'inclut que les résultats des bases de données avec des résultats

Eh bien, d'abord, arrêtez d'utiliser sp_MSforEachDb . Oh, les problèmes (si vous voulez une preuve, voir ici ).

Que diriez-vous :

DECLARE @cmd NVARCHAR(MAX) = N'', @sql NVARCHAR(MAX) = N'';

SELECT @cmd += N'IF EXISTS (SELECT 1 FROM '
  + QUOTENAME(name) + '.sys.tables WHERE name = N''Tabs'')
  SET @sql += N''UNION ALL 
    SELECT ''''' + name + ''''',T.TabName
    FROM ' + QUOTENAME(name) + '.dbo.Tabs AS T
    WHERE EXISTS 
    (
      SELECT 1 FROM ' + QUOTENAME(name) + '.dbo.TabModules AS TM
        WHERE TM.TabID = T.TabID
        AND TM.mID IN -- this should probably be exists too
        ( 
          ...
        )
    )
'''
FROM sys.databases 
  WHERE state = 0 -- assume you only want online databases
  AND database_id > 4; -- assume you don't want system dbs

EXEC sp_executesql @cmd, N'@sql NVARCHAR(MAX) OUTPUT', @sql OUTPUT;

SET @sql = STUFF(@sql, 1, 10, '') + N' ORDER BY TabName;';   

PRINT @sql; -- this will appear truncated, but trust me, it is not truncated
-- EXEC sp_executesql @sql;

Si vous voulez vraiment un nombre inconnu et arbitraire d'ensembles de résultats séparés, le changement est simple.

DECLARE @cmd NVARCHAR(MAX) = N'', @sql NVARCHAR(MAX) = N'';

SELECT @cmd += N'IF EXISTS (SELECT 1 FROM '
  + QUOTENAME(name) + '.sys.tables WHERE name = N''Tabs'')
  SET @sql += N''SELECT ''''' + name + ''''',T.TabName
    FROM ' + QUOTENAME(name) + '.dbo.Tabs AS T
    WHERE EXISTS 
    (
      SELECT 1 FROM ' + QUOTENAME(name) + '.dbo.TabModules AS TM
        WHERE TM.TabID = T.TabID
        AND TM.mID IN -- this should probably be exists too
        ( 
          ...
        )
    )
 ORDER BY T.TabName;
 '';'
FROM sys.databases 
  WHERE state = 0 -- assume you only want online databases
  --AND database_id > 4; -- assume you don't want system dbs

EXEC sp_executesql @cmd, N'@sql NVARCHAR(MAX) OUTPUT', @sql OUTPUT;

PRINT @sql; -- this will appear truncated, but trust me, it is not truncated
-- EXEC sp_executesql @sql;