SQL Server 2008 delete all tables under special schema

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

    I know this is an old thread but I think the easiest way to do this is by using the undocumented sp_MSforeachtable stored procedure:

    EXEC sp_MSforeachtable
      @command1 = 'DROP TABLE ?'
    , @whereand = 'AND SCHEMA_NAME(schema_id) = ''your_schema_name'' '
    

    A detailed report on this stored procedure can be found here, but in case the link goes dead here are the highlights:

    sp_MSforeachtable is a stored procedure that is mostly used to apply a T-SQL command to every table, iteratively, that exists in the current database.
    [...]
    realized that the question mark (?) it is used as the replacement of the table and during the execution it will be replaced by the appropriate table name.

    @command1, @command2, @command3
    sp_MSforeachtable stored procedure requires at least one command to be executed (@command1) but it allows up to 3 commands to be executed. Note that it will start to execute first the @command1 and then @command2 and @command3 by the last and this for each table.

    @precommand
    Use this parameter to provide a command to be executed before the @command1. It is useful to set variable environments or perform any kind of initialization.

    @postcommand
    Use this parameter to provide a command to be executed after all the commands being executed successfully. It is useful for control and cleanup processes.

    @replacechar
    By default, a table is represented by the question mark (?) character. This parameter allows you to change this character.

    @whereand
    By default, sp_MSforeachtable is applied to all user tables in the database. Use this parameter to filter the tables that you want to work with. On the next section, I will explain how you can filter the tables.

提交回复
热议问题