SQL Server 2008 delete all tables under special schema

后端 未结 13 1520
广开言路
广开言路 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:31

    I combined the answers from @raider33 and @Kevo to one solutions for direct execution.

    DECLARE @SqlStatement NVARCHAR(MAX)
    DECLARE @schema varchar(30) = 'SCHEMA_NAME';
    
    select @SqlStatement = COALESCE(@SqlStatement,'') + 'ALTER TABLE '+@schema+'.' + t.name + ' drop constraint ' + 
    OBJECT_NAME(d.constraint_object_id)  + ';' + CHAR(13) + CHAR(10)
    from sys.tables t 
        join sys.foreign_key_columns d on d.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;
    
    SELECT @SqlStatement += 
        COALESCE(@SqlStatement, '') + 'DROP TABLE ' + @schema +'.'+ QUOTENAME(TABLE_NAME) + ';'  + CHAR(13) + CHAR(10)
    FROM INFORMATION_SCHEMA.TABLES
    WHERE TABLE_SCHEMA = @schema
    
    EXECUTE sp_executesql @SqlStatement
    

提交回复
热议问题