我需要在Sql server 2005中进行查询。我有一个列名。有了这个,我需要找到一个数据库名称和表名。有没有办法找到它?
答案 0 :(得分:4)
来自SO的姊妹网站“StackExchange”:
SELECT t.name AS table_name,
SCHEMA_NAME(schema_id) AS schema_name,
c.name AS column_name
FROM sys.tables AS t
INNER JOIN sys.columns c ON t.OBJECT_ID = c.OBJECT_ID
WHERE c.name LIKE '%EmployeeID%'
ORDER BY schema_name, table_name;
答案 1 :(得分:0)
可能,这个脚本对你有帮助 -
DECLARE @SearchColumnName SYSNAME
SELECT @SearchColumnName = 'EmployeeID'
IF EXISTS(
SELECT 1
FROM tempdb.dbo.sysobjects
WHERE id = OBJECT_ID('tempdb.dbo.#DB')
) DROP TABLE #DB
CREATE TABLE #DB
(
[DB_NAME] SYSNAME
, [OBJECT_NAME] SYSNAME
, [COLUMN_NAME] SYSNAME
)
DECLARE @SQL NVARCHAR(500)
SELECT @SQL = 'USE [?]
INSERT INTO #DB
(
[DB_NAME]
, [OBJECT_NAME]
, [COLUMN_NAME]
)
SELECT
DB_NAME()
, s.name + ''.'' + o.name
, c.name
FROM (
SELECT
c.[object_id]
, c.name
FROM sys.columns c WITH (NOWAIT)
WHERE c.name LIKE ''%'' + ''' + @SearchColumnName+ ''' + ''%''
) c
JOIN sys.objects o WITH (NOWAIT) ON c.[object_id] = o.[object_id]
JOIN sys.schemas s WITH (NOWAIT) ON o.[schema_id] = s.[schema_id]
WHERE o.type = ''U'''
EXEC sys.sp_MSforeachdb @SQL
SELECT *
FROM #DB
ORDER BY [DB_NAME], [OBJECT_NAME]