SQL Server 2008 delete all tables under special schema

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

    Drop all tables in schema , can be modified to return any subset of tables.

    declare @schema varchar(10) = 'temp' 
    declare @max_number_of_tables int = 1000
    declare @sql nvarchar(max)
    declare @index int = 0
    
    
    while (
    select count(*)
    from
        sys.objects obj
        join sys.schemas s
            on (s.schema_id=obj.schema_id)
    where
        s.name= @schema 
        and obj.type = 'U'
        AND obj.is_ms_shipped = 0x0) > 0 and @index < @max_number_of_tables
    begin
      set @index = @index+1
    
      select top 1
        @sql = N'DROP TABLE [' + @schema + '].[' + obj.name + ']'
      from
        sys.objects obj
        join sys.schemas s
            on (s.schema_id=obj.schema_id)
      where
        s.name = @schema
        and obj.type = 'U'
        AND obj.is_ms_shipped = 0x0
      order by obj.name
    
      print @sql
    
      execute(@sql)
    end
    

提交回复
热议问题