SQL Server 2008 delete all tables under special schema

后端 未结 13 1523
广开言路
广开言路 2021-01-30 01:02

Hello I would like to know is is possible to drop all tables in database what was created under custom schema for example DBO1...with one sql query or special script.

T

13条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-30 01:14

    Building on the other answers, here is a stored procedure spDropSchema that drops all objects in a schema and the schema itself.

    Note that the procedure tries to drop sequence objects too, so it will only work on SQL Server 2012 and above.

    IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'spDropSchema')
        BEGIN
            DROP  PROCEDURE  spDropSchema
        END
    GO
    
    CREATE PROCEDURE spDropSchema(@Schema nvarchar(200))
    AS
    
    DECLARE @Sql NVARCHAR(MAX) = '';
    
    --constraints
    SELECT @Sql = @Sql + 'ALTER TABLE '+ QUOTENAME(@Schema) + '.' + QUOTENAME(t.name) + ' DROP CONSTRAINT ' + QUOTENAME(f.name)  + ';' + CHAR(13)
    FROM sys.tables t 
        inner join sys.foreign_keys f on f.parent_object_id = t.object_id 
        inner join sys.schemas s on t.schema_id = s.schema_id
    WHERE s.name = @Schema
    ORDER BY t.name;
    
    --tables
    SELECT @Sql = @Sql + 'DROP TABLE '+ QUOTENAME(@Schema) +'.' + QUOTENAME(TABLE_NAME) + ';' + CHAR(13)
    FROM INFORMATION_SCHEMA.TABLES
    WHERE TABLE_SCHEMA = @Schema AND TABLE_TYPE = 'BASE TABLE'
    ORDER BY TABLE_NAME
    
    --views
    SELECT @Sql = @Sql + 'DROP VIEW '+ QUOTENAME(@Schema) +'.' + QUOTENAME(TABLE_NAME) + ';' + CHAR(13)
    FROM INFORMATION_SCHEMA.TABLES
    WHERE TABLE_SCHEMA = @Schema AND TABLE_TYPE = 'VIEW'
    ORDER BY TABLE_NAME
    
    --procedures
    SELECT @Sql = @Sql + 'DROP PROCEDURE '+ QUOTENAME(@Schema) +'.' + QUOTENAME(ROUTINE_NAME) + ';' + CHAR(13)
    FROM INFORMATION_SCHEMA.ROUTINES
    WHERE ROUTINE_SCHEMA = @Schema AND ROUTINE_TYPE = 'PROCEDURE'
    ORDER BY ROUTINE_NAME
    
    --functions
    SELECT @Sql = @Sql + 'DROP FUNCTION '+ QUOTENAME(@Schema) +'.' + QUOTENAME(ROUTINE_NAME) + ';' + CHAR(13)
    FROM INFORMATION_SCHEMA.ROUTINES
    WHERE ROUTINE_SCHEMA = @Schema AND ROUTINE_TYPE = 'FUNCTION'
    ORDER BY ROUTINE_NAME
    
    --sequences
    SELECT @Sql = @Sql + 'DROP SEQUENCE '+ QUOTENAME(@Schema) +'.' + QUOTENAME(SEQUENCE_NAME) + ';' + CHAR(13)
    FROM INFORMATION_SCHEMA.SEQUENCES
    WHERE SEQUENCE_SCHEMA = @Schema
    ORDER BY SEQUENCE_NAME
    
    --types
    SELECT @Sql = @Sql + 'DROP TYPE ' + QUOTENAME(@Schema) + '.' + QUOTENAME(t.name) + ';' + CHAR(13)
    FROM sys.types t
        INNER JOIN sys.schemas s ON t.schema_id = s.schema_id
    WHERE t.is_user_defined = 1 AND
        s.name  = @Schema
    ORDER BY s.name
    
    SELECT @Sql = @Sql + 'DROP SCHEMA '+ QUOTENAME(@Schema) + ';' + CHAR(13)
    
    EXECUTE sp_executesql @Sql
    
    GO
    

提交回复
热议问题