我的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"
谢谢!
答案 0 :(得分: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
结果如下:
答案 1 :(得分: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
;然后运行那些并得到结果。
如果databases
超过100 results to text
,请使用selects
,因为要投放网格,您最多只能获得100 {{1}}次