sql server - MSSQL T-SQL Table Hierachy including parent/child(group) -



sql server - MSSQL T-SQL Table Hierachy including parent/child(group) -

i have query lists databases table hierarchy in relation level of fk/checks on referenced tables , columns.

this depict order in info deleted/inserted.

problem is, within want include path i.e. levels 1 through 'x' grouping path each follows (some might have multiple paths through levels).

anyone have suggestions, utilize cte recursively grab level. perchance utilize fk referenced table-name?

;with ctetbhierarchy ( select distinct 1 levelid , object_schema_name(parent.object_id) tableowner , parent.name tablename , parent.object_id tbobjid , object_name(refkey.referenced_object_id) referenced_tablename , refkey.referenced_object_id , refkey.referenced_column_id sys.objects parent left outer bring together sys.foreign_key_columns refkey on refkey.parent_object_id = parent.object_id , refkey.parent_object_id <> refkey.referenced_object_id , refkey.constraint_column_id = 1 refkey.parent_object_id null , parent.type = 'u' , parent.name <> 'dtproperties' union /* add together tables reference anchor rows */ select h.levelid + 1 , object_schema_name(parent.object_id) tableowner , object_name(parent.object_id) tablename , parent.object_id tbobjid , object_name(refkey.referenced_object_id) referenced_tablename , refkey.referenced_object_id , refkey.referenced_column_id sys.objects parent inner bring together sys.foreign_key_columns refkey on refkey.parent_object_id = parent.object_id , refkey.parent_object_id <> refkey.referenced_object_id , refkey.constraint_column_id = 1 inner bring together ctetbhierarchy h on h.tbobjid = refkey.referenced_object_id parent.type = 'u' , parent.name <> 'dtproperties' ) select distinct a.levelid, a.tableowner, a.tablename, a.referenced_tablename, cols.name referenced_colname, replace(a.tablename,(left(substring(a.tablename, charindex('.',a.tablename), 50),50)),'') tablearea, replace(a.referenced_tablename,(left(substring(a.referenced_tablename, charindex('.',a.referenced_tablename), 50),50)),'') reftablearea ctetbhierarchy left bring together sys.columns cols on a.referenced_object_id = cols.object_id , a.referenced_column_id = cols.column_id order levelid asc , tablename;

sql sql-server tsql foreign-keys

Comments

Popular posts from this blog

php - Android app custom user registration and login with cookie using facebook sdk -

django - Access session in user model .save() -

php - .htaccess Multiple Rewrite Rules / Prioritizing -