需要有关sql server表的建议

时间:2011-08-31 15:24:09

标签: sql sql-server tsql

有没有人知道如何使用sql server系统表获取表名和列名?

示例:我知道数据库中的某个表有一个包含ID = 1125412的字段。

是否有办法在数据库上运行全局查询,以获取此数据所在的列名和表名。

这是否可行,如果您知道列名,并且您想知道它所属的表名?

2 个答案:

答案 0 :(得分:7)

这是超级讨厌,但它会起作用:

-- Finding all tables with an ID column
SELECT SCHEMA_NAME(T.schema_id) SchemaName,
       T.name TableName
INTO #FoundTables
FROM sys.tables T INNER JOIN
     sys.columns C ON T.object_id = C.object_id
WHERE C.name = 'ID';

DECLARE @SchemaName NVarChar(100),
        @TableName NVarChar(100),
        @SQL NVarChar(2000);
-- Dynamically build a SELECT statement
WHILE (EXISTS (SELECT * FROM #FoundTables)) BEGIN
  SELECT TOP 1 @SchemaName = SchemaName, @TableName = TableName,
    @SQL = 'SELECT * FROM $SchemaName.$TableName WHERE ID = 1125412;'
  FROM #FoundTables;

  SELECT @SQL =
    REPLACE(REPLACE(@SQL, '$SchemaName', @SchemaName), '$TableName', @TableName);
  EXEC (@SQL);

  DELETE FROM #FoundTables
  WHERE SchemaName = @SchemaName
    AND TableName = @TableName;
END;

DROP TABLE #FoundTables;

答案 1 :(得分:0)

我使用以下查询:

SELECT  sys.sysobjects.id, 
    sys.sysobjects.name AS TableName, 
    sys.syscolumns.colid, 
    sys.syscolumns.name AS ColumnName, 
    sys.systypes.name AS DataType, 
    sys.syscolumns.isnullable AS AllowNull
FROM sys.syscolumns LEFT OUTER JOIN
    sys.systypes ON sys.syscolumns.xtype = sys.systypes.xtype 
    RIGHT OUTER JOIN sys.sysobjects ON sys.syscolumns.id = sys.sysobjects.id
WHERE (sys.sysobjects.xtype = 'U') AND (sys.systypes.name <> 'sysname')
ORDER BY TableName, sys.syscolumns.colid