gpt4 book ai didi

sql - 查找表的数据库位置

转载 作者:行者123 更新时间:2023-12-02 22:32:56 28 4
gpt4 key购买 nike

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

我需要这样的东西:

SELECT DATABASE_NAME FROM SQLSERVER WHERE TABLE= "TBL_PRODUCTS"

添加: 现在,我需要知道某些 View 和存储过程的数据库位置

像这样:

SELECT DATABASE_NAME FROM SQLSERVER WHERE VIEW= "VW_PRODUCTS"

SELECT DATABASE_NAME FROM SQLSERVER WHERE StoredProcedure= "SP_PRODUCTS"

谢谢!

最佳答案

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

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

结果应该是这样的:

Result Table

Source

关于sql - 查找表的数据库位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11936253/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com