通过在SQL Server 20008中搜索数据来查询获取表名

时间:2014-01-17 07:18:36

标签: sql-server

如果有人知道,请通过在完整的数据库中搜索数据来提供查询以获取表名和数据库名称。

1 个答案:

答案 0 :(得分:0)

您可以在单个数据库中搜索表名称,如下所示:

USE YourDatabaseName

SELECT *
FROM sys.Tables
WHERE name LIKE '%SearchText%'

您还可以在所有数据库中搜索表格名称,例如Pinal Dave描述here

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