Need advice on sql server tables
Has anyone an idea about how to get Table name and column name using sql server system tables?
Example : I know that a table somewhere in my database has a field containing an ID = 1125412.
Is there a way to run a global query on the database, to get column name and table nam开发者_如何学JAVAe where this data exists.
Is this doable, if you know a column name, and you want to know the table name to where it belongs?
This is super nasty, but it will work:
-- 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;
I use the following query:
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
精彩评论