SQL Server 2008 delete all tables under special schema

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

    Building on chris LB's answer, I added

    GROUP BY d.constraint_object_id, t.name
    

    because I saw duplicate constraint deletions in my query. constraint_object_id is the FK Constraint ID, as noted at https://msdn.microsoft.com/en-us/library/ms186306.aspx

    DECLARE @SqlStatement NVARCHAR(MAX),
            @Schema NVARCHAR(20)
    
    SET @Schema = 'aa'
    
    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 t.object_id = d.parent_object_id 
        INNER JOIN sys.schemas s on t.schema_id = s.schema_id
    WHERE s.name = @Schema
    GROUP BY d.constraint_object_id, t.name
    ORDER BY t.name;
    

提交回复
热议问题