返回包含指定表的数据库列表 -
询问:
DECLARE
@SQL NVARCHAR(MAX)
, @table_name SYSNAME
SELECT @table_name = 'dbo.test'
IF OBJECT_ID('tempdb.dbo.#db_temp') IS NOT NULL
DROP TABLE #db_temp
CREATE TABLE #db_temp (db_nm SYSNAME)
SELECT @SQL = (
SELECT '
USE [' + d.name + '];
INSERT INTO #db_temp (db_nm)
SELECT DB_NAME()
WHERE EXISTS(
SELECT 1
FROM sys.objects
WHERE [object_id] = OBJECT_ID(''' + @table_name + ''')
AND [type] = ''U''
)'
FROM sys.databases d
WHERE d.name NOT IN ('master', 'tempdb', 'model', 'msdb')
AND d.state_desc != 'OFFLINE'
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)')
EXEC sys.sp_executesql @SQL
SELECT *
FROM #db_temp dt
输出:
USE [...];
INSERT INTO #db_temp (db_nm)
SELECT DB_NAME()
WHERE EXISTS(
SELECT 1
FROM sys.objects
WHERE [object_id] = OBJECT_ID('...')
AND [type] = 'U'
)
...