2

我的 SQL Server 2008 中有几个数据库。我忘记了一些表来自哪里,所以我需要询问是否有这样的查询可以找到某个表的数据库位置?

我需要这样的东西:

SELECT DATABASE_NAME FROM SQLSERVER WHERE TABLE= "TBL_PRODUCTS"

补充:现在,我需要知道某些视图和存储过程的数据库位置

像这样的东西:

SELECT DATABASE_NAME FROM SQLSERVER WHERE VIEW= "VW_PRODUCTS"

SELECT DATABASE_NAME FROM SQLSERVER WHERE StoredProcedure= "SP_PRODUCTS"

谢谢!

4

2 回答 2

3

以下过程将完成这项工作:

CREATE PROCEDURE usp_FindTableNameInAllDatabase
@TableName VARCHAR(256)
AS
DECLARE @DBName VARCHAR(256)
DECLARE @varSQL VARCHAR(512)
DECLARE @getDBName CURSOR
SET @getDBName = CURSOR FOR
SELECT name
FROM sys.databases
CREATE TABLE #TmpTable (DBName VARCHAR(256),
SchemaName VARCHAR(256),
TableName VARCHAR(256))
OPEN @getDBName
FETCH NEXT
FROM @getDBName INTO @DBName
WHILE @@FETCH_STATUS = 0
BEGIN
SET @varSQL = 'USE ' + @DBName + ';
INSERT INTO #TmpTable
SELECT '''+ @DBName + ''' AS DBName,
SCHEMA_NAME(schema_id) AS SchemaName,
name AS TableName
FROM sys.tables
WHERE name LIKE ''%' + @TableName + '%'''
EXEC (@varSQL)
FETCH NEXT
FROM @getDBName INTO @DBName
END
CLOSE @getDBName
DEALLOCATE @getDBName
SELECT *
FROM #TmpTable
DROP TABLE #TmpTable
GO
EXEC usp_FindTableNameInAllDatabase 'Address'
GO 

结果将如下所示:

结果表

资源

于 2012-08-13T14:24:12.060 回答
2

做这个

Use Master
Go

    select 
    'select '''+CAST(name as varchar(200))+''' from '+CAST(name as varchar(200))+'.sys.tables where name = yourTableName' 
    from sysdatabases

替换 yourTableName为您的表的名称,' '

你会得到selects; 然后运行这些并会得到结果。如果超过 100 databases,请使用,因为要网格化,您最多results to text只能得到 100selects

于 2012-08-13T14:41:43.707 回答