对所有数据库执行查询

时间:2018-05-29 14:45:30

标签: sql-server

我想针对所有数据库执行以下查询。

DECLARE @DB_NAME VARCHAR(30)
SET @DB_NAME = 'Employee';

WITH D
AS
(
SELECT @DB_NAME AS DB_NAME, T.NAME AS TABLE_NAME, C.NAME AS COLUMN_NAME
FROM SYS.tables T
INNER JOIN SYS.columns C 
ON T.object_id = C.object_id
WHERE C.name LIKE '%AFFINITY%'
or c.name = 'affinity'
)
SELECT DB_NAME, TABLE_NAME, MAX(COLUMN_NAME) AS COLUMN_NAME FROM D
GROUP BY DB_NAME, TABLE_NAME
ORDER BY TABLE_NAME`

2 个答案:

答案 0 :(得分:0)

有无证件

EXEC sp_MSforeachdb @command

(命令中的?将被数据库名称替换。)

否则您需要sp_executesql并将光标放在sys.databases上。

后者是受支持的,sp_MSforeachdb不是,所以对于任何类型的生产系统,光标都是更好的选择(即使最初有一点工作)。当然,您对sys.databases的查询可以过滤数据库列表。

答案 1 :(得分:0)

小心使用:

我假设您在每个必需的数据库中都有MYTABLE,否则这不会有效。

DECLARE @MYDATABASES NVARCHAR(50)

CREATE TABLE #MYBASE(DB NVARCHAR(50))

DECLARE dbcur CURSOR FOR
SELECT name
FROM sys.databases s 
WHERE name not in ('master', 'tempdb', 'msdb') --use this to select all databases but system
--WHERE NAME IN ('myfirstDB', 'mysecondDB', 'mythirdDB') --use this to select only certain databases
OPEN dbcur 
FETCH dbcur INTO @MYDATABASES
WHILE @@FETCH_STATUS = 0
BEGIN
/* MY STATEMENT */

DECLARE @SQLSTATEMENT NVARCHAR(MAX)

SELECT @SQLSTATEMENT = N'
SELECT  @DB --EDIT WITH YOUR COLUMNS
FROM '+@MYDATABASES+'.dbo.MYTABLE --EDIT THIS
'
INSERT INTO #MYBASE
EXEC sp_executesql @SQLSTATEMENT, N'@DB NVARCHAR(50)', @DB = @MYDATABASES

/* END STATEMENT */
FETCH NEXT FROM dbcur INTO @MYDATABASES
END
CLOSE dbcur
DEALLOCATE dbcur
SELECT DISTINCT * FROM #MYBASE
ORDER BY DB
DROP TABLE #MYBASE