sql >> データベース >  >> RDS >> Sqlserver

sp_MSforeachdb:結果のあるデータベースからの結果のみを含める

    まず、sp_MSforEachDb の使用をやめる .ああ、問題 (証拠が必要な場合は、こちら ).

    どうですか:

    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;
      

    未知の任意の数の別個の結果セットが本当に必要な場合、変更は簡単です。

    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;
      

    1. INDEXとUNIQUEINDEXの両方を指定する必要がありますか?

    2. Oracle分散データベースとMSVC

    3. 複数の値を持つFIND_IN_SET

    4. 特定の時間間隔で作成された日時間のMySQLの平均時間数