T-SQL目录表,列(T-SQL List Tables, Columns)

2019-09-03 11:42发布

在T-SQL(SQL Server 2000中)。 如何列出数据库中的所有表和列? 此外,在一个单独的查询是有办法来列出所有列与数据类型和约束(空值,等等)沿着。 谢谢。

Answer 1:

请检查出的信息模式 。

select *
from MyDatabaseName.information_schema.columns
order by table_name, ordinal_position


Answer 2:

很多方法可以做到这一点。 下面是几个方法,你可以列出:

选项1:

SELECT db_name() as DATABASE_NAME, TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME, ORDINAL_POSITION,
       COLUMN_DEFAULT, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH,
       NUMERIC_PRECISION, NUMERIC_PRECISION_RADIX, NUMERIC_SCALE,
       DATETIME_PRECISION
FROM INFORMATION_SCHEMA.COLUMNS

选项2:

DECLARE @SQL VARCHAR(8000)
SELECT  @SQL = ''
SELECT  @SQL = @SQL + 'UNION
SELECT ''' + name + ''' [DataBaseName], t.name [TableName], c.name [ColumnName], st.name [DataType] FROM ' + name + '..sysobjects t INNER JOIN ' + name + '..syscolumns c ON t.id = c.id INNER JOIN '+ name + '..systypes st on c.xtype = st.xtype where t.xtype = ''U'''
FROM master..sysdatabases
WHERE name IN ('databasename1', 'databaseName2')  -- change here !!
SELECT @SQL = RIGHT(@SQL, LEN(@SQL)-5) + ' ORDER BY 1, 2, 3'
EXEC(@SQL)

方案3:

select db_name() as database_name
    ,table_name = sysobjects.name
    ,column_name = syscolumns.name
    ,datatype = systypes.name
    ,length = syscolumns.length
from sysobjects
inner join syscolumns on sysobjects.id = syscolumns.id
inner join systypes on syscolumns.xtype = systypes.xtype
where sysobjects.xtype = 'U'
order by sysobjects.name
    ,syscolumns.colid


文章来源: T-SQL List Tables, Columns