Sql-Server

需要在所有數據庫中執行 select 語句

  • May 4, 2018

我正在嘗試跨多個數據庫執行如下查詢

select ParamValue from Table1 where paramname = 'SYSTEM_LICENSE'

每個數據庫的名稱類似於下面的名稱,並且應排除某些數據庫。

“客戶_123”

我查看了使用 sp_MSforeachdb 但它不受支持且執行不正常。我試圖弄清楚如何編寫游標,但沒有成功。在這一點上,只是向能夠真正寫出我想要做的事情的人尋求幫助。

這是我使用的“在每個數據庫上做一些事情”模板,稍微適應了您的範例:

--Create a table to hold the query results
CREATE TABLE #licenselist
   (dbid smallint, dbname sysname, system_license varchar(99));

DECLARE @fixedname nvarchar(150);

--Include or exclude whatever databases you want
DECLARE dbCursor CURSOR FOR
   SELECT REPLACE(QUOTENAME(name),'''','''''') --For db names with annoying characters
   FROM master.sys.databases
   WHERE state_desc = 'ONLINE'
   AND HAS_DBACCESS(name) = 1                  --Added at @SolomonRutzky's suggestion
   AND name NOT IN ('master','msdb','model','tempdb');

OPEN dbCursor;
FETCH NEXT FROM dbCursor INTO @fixedname;

WHILE @@FETCH_STATUS = 0   
BEGIN   
      EXEC ('USE ' + @fixedname + ';' + 
       'INSERT INTO #licenselist
        SELECT DB_ID() as dbid, DB_NAME() as dbname, ParamValue as system_license
        FROM Table1 
        WHERE paramname = ''SYSTEM_LICENSE'';');

      FETCH NEXT FROM dbCursor INTO @fixedname;
END;   

CLOSE dbCursor;
DEALLOCATE dbCursor;

SELECT * FROM #licenselist 

DROP TABLE #licenselist

編輯:簡化了一點,刪除了原始的 @dbname 變數,而是在原始查詢中修復了它。

引用自:https://dba.stackexchange.com/questions/205618