SQL Server 2008 delete all tables under special schema

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

    Just in case it helps someone, I added this as a stored procedure to the master database to allow it to conveniently used on any db / schema.

    It can be called like this:

    EXEC master.dbo.dropTablesInSchema 'my_db', 'dbo
    

    Stored procedure create script:

    CREATE PROC [master].[dbo].[dropTablesInSchema]
        @db nvarchar(max),
        @schema nvarchar(max)
    AS
    BEGIN
        DECLARE @Tables TABLE (name nvarchar(max))
        INSERT INTO @Tables
        EXEC ('SELECT TABLE_NAME FROM [' + @db + '].INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = ''' + @schema + ''' and TABLE_TYPE =''BASE TABLE''')
    
        DECLARE @SqlStatement NVARCHAR(MAX)
        SELECT @SqlStatement = 
            COALESCE(@SqlStatement, N'') + N'DROP TABLE [' + @db + '].[' + @schema + '].' + QUOTENAME(NAME) + N';' + CHAR(13)
        FROM @Tables
    
        EXEC(@SqlStatement)
    
    END
    

提交回复
热议问题