SQL Server: drop table cascade equivalent?

前端 未结 6 1540
难免孤独
难免孤独 2020-11-29 06:14

In oracle, to drop all tables and constraints you would type something like

DROP TABLE myTable CASCADE CONSTRAINTS PURGE;

and this would co

6条回答
  •  忘掉有多难
    2020-11-29 06:23

    This is all fun and games until some table references your table...

    Then I must alter the code provided like so :

    CREATE PROCEDURE _cascadeConstraints @database nvarchar(30) = NULL, @table nvarchar(60) = NULL
    as
    DECLARE @sql nvarchar(255)
    WHILE EXISTS(select * from INFORMATION_SCHEMA.TABLE_CONSTRAINTS where constraint_catalog = @database and table_name = @table)
    BEGIN
        select    @sql = 'ALTER TABLE ' + @table + ' DROP CONSTRAINT ' + CONSTRAINT_NAME 
        from    INFORMATION_SCHEMA.TABLE_CONSTRAINTS 
        where    constraint_catalog = @database and 
                table_name = @table
        select @sql = 'ALTER TABLE ' + tc.TABLE_NAME + ' DROP CONSTRAINT ' + tc.CONSTRAINT_NAME
          from INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc join
                      INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS rc on
                       (rc.CONSTRAINT_CATALOG = tc.CONSTRAINT_CATALOG and
                        rc.CONSTRAINT_NAME = tc.CONSTRAINT_NAME) join
                      INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc_pk on
                       (tc_pk.CONSTRAINT_CATALOG = rc.CONSTRAINT_CATALOG and
                        tc_pk.CONSTRAINT_NAME = rc.UNIQUE_CONSTRAINT_NAME)
         where tc.constraint_catalog = @database
           and tc_pk.TABLE_NAME = @table
        exec    sp_executesql @sql
    END
    go
    

提交回复
热议问题