I spent several hours mining Google and tweaking to get this query right. This has never been a technical blog, but considering what a pain this was to chase down, I figured I should post it here for others.
This query will list all the tables and columns in a SQL Server 2000 database, including column data type, length, precision, scale, nullable flag, if the column is part of a unique constraint, if the column is part of the primary key, the foreign table referenced by the column if it is a foreign key, and the default value of the column if it has one.
The output is suitable for pasting into Excel or Word to create database reports. (Yes I'm sure there are 3rd party tools, and stored procedures to get all this info, but what I needed was ONE query which did it all and returned it as this query does.)
You can see a screenshot of the output here.select T.name as TableName, C.colorder, C.name as ColumnName, TY.name as datatype,
c.length, c.prec, c.scale, c.isnullable, UO.name as UniqueConstraint,
IX.name as PKConstraint, SR.name as ReferencesTable, SM.Text as DefaultValue from sysobjects as T inner join syscolumns as C on (C.id = T.id) inner join systypes as TY on (TY.xtype = C.xtype) left join sysindexkeys as K on C.colid = K.colid and K.id=T.id left join sysindexes as I on I.id=T.id and I.indid=K.indid left join sysobjects as IX on IX.parent_obj=T.id and IX.name = I.name and IX.xtype='PK' left join sysconstraints as CO on (C.colid=CO.colid and CO.id=T.id) left join sysforeignkeys as FK on (T.id = FK.fkeyid and FK.constid=CO.constid) left join sysobjects as SR on (SR.id = FK.rkeyid) left join syscomments SM on C.cdefault = SM.id left join sysindexkeys as UK on C.colid = UK.colid and UK.id=T.id left join sysindexes as UI on UI.id=T.id and UI.indid=K.indid left join sysobjects as UO on (UO.parent_obj=T.id and UO.name=UI.name and UO.xtype='UQ') where T.xtype = 'U' order by T.name, C.colorder;

Search
Recent Comments




