Note that there are some explanatory texts on larger screens.

plurals
  1. POSQL-Server Query on the Results of Itself
    primarykey
    data
    text
    <p>I'm trying to identify the risks in deleting tables from my database.</p> <p>The database is large and contains hundreds of tables.</p> <p>I have a query that returns Foreign Keys associated with a table. So I can feed it table names I want to delete and it tells me what tables rely on columns it has. So I will also have to delete the tables that are returned.</p> <p>My problem comes that as I would then need to delete those tables, I'd like to see any other tables that depend on the initial results.</p> <p>As such I believe I need my query to loop calling itself with the results of it's last run, until there are no more unique results.</p> <p>Is this possible? Is there an easier way of doing this?</p> <p>EDIT: Here's the query:</p> <pre><code>SELECT PK.TABLE_NAME AS PrimaryTable, FK.TABLE_NAME AS ForeignTable, PT.COLUMN_NAME AS PrimaryColumn, CU.COLUMN_NAME AS ForeignColumn, C.CONSTRAINT_NAME AS ConstraintName FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS C INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS FK ON C.CONSTRAINT_NAME = FK.CONSTRAINT_NAME INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS PK ON C.UNIQUE_CONSTRAINT_NAME = PK.CONSTRAINT_NAME INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE CU ON C.CONSTRAINT_NAME = CU.CONSTRAINT_NAME INNER JOIN ( SELECT i1.TABLE_NAME, i2.COLUMN_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS i1 INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE i2 ON i1.CONSTRAINT_NAME = i2.CONSTRAINT_NAME WHERE i1.CONSTRAINT_TYPE = 'PRIMARY KEY' ) PT ON PT.TABLE_NAME = PK.TABLE_NAME WHERE PK.TABLE_NAME IN ('Table1','Table2') ORDER BY 1,2,3,4 </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload