Tuesday, December 18, 2007

Querying the system catalog for tables, columns and constraints

Querying the system catalog for tables, columns and constraints
--------------------------------------------------------------------------------
// show tables and their columns in their original order
SELECT so.name, sc.name, st.name, sc.length, sc.prec, sc.scale, sc.status
FROM dbo.sysobjects so, dbo.syscolumns sc, dbo.systypes st
WHERE so.type IN ( 'V', 'U' )
AND so.id = sc.id
AND sc.type = st.type
AND st.usertype NOT IN ( 18, 25 )
AND so.name = "RTI_IMPORT_PROVRVU"
ORDER BY sc.colid

// show referential integrity constraints
SELECT so.name table_name,
sc.name column_name ,
constr_obj.name constraint_name,
ref_obj.name referenced_table_name,
ref_col.name referenced_column_name
FROM sysobjects so,
sysobjects constr_obj,
sysreferences sr,
sysobjects ref_obj,
syscolumns sc,
syscolumns ref_col
WHERE constr_obj.id = sr.constrid
AND sr.tableid = so.id
AND sr.reftabid = ref_obj.id
AND sr.fokey1 = sc.colid
AND sr.tableid = sc.id
AND sr.refkey1 = ref_col.colid
AND ref_obj.id = ref_col.id

No comments: