From time to time, I need to drop tables that have PK constraints applied already. Deleting manually is really cumbersome as you have to take care of dependencies first. Is there a script to break all constraints among tables so that I could apply the following script to drop tables?The example shows how to drop tables with the name of HUB%
DECLARE @id varchar(255) DECLARE @dropCommand varchar(255)
if exists (select '['+TABLE_SCHEMA+']'+'.'+table_name from INFORMATION_SCHEMA.TABLES a where a.TABLE_NAME like 'HUB%' or a.table_name like 'HUB%') begin
DECLARE tableCursor CURSOR FOR
select '['+TABLE_SCHEMA+']'+'.'+table_name from INFORMATION_SCHEMA.TABLES a where a.TABLE_NAME like 'STG_STARS%' or a.table_name like 'HUB%' and a.TABLE_SCHEMA = 'dbo'
OPEN tableCursor FETCH next FROM tableCursor INTO @id
WHILE @@fetch_status=0 BEGIN SET @dropcommand = 'drop table ' + @id EXECUTE(@dropcommand) FETCH next FROM tableCursor INTO @id end
end CLOSE tableCursor DEALLOCATE tableCursor
Below is the script to drop all constraints
DECLARE @database nvarchar(50) DECLARE @table nvarchar(50) set @database = 'ERS_DS' --set @table = 'tabs' declare @schema nvarchar(128), @tbl nvarchar(128), @constraint nvarchar(128) DECLARE @sql nvarchar(255) declare cur cursor fast_forward for select distinct cu.constraint_schema, cu.table_name, cu.constraint_name from information_schema.table_constraints tc join information_schema.referential_constraints rc on rc.unique_constraint_name = tc.constraint_name join information_schema.constraint_column_usage cu on cu.constraint_name = rc.constraint_name where tc.constraint_catalog = @database and tc.table_name like 'HUB%' open cur fetch next from cur into @schema, @tbl, @constraint while @@fetch_status <> -1 begin select @sql = 'ALTER TABLE ' + @schema + '.' + @tbl + ' DROP CONSTRAINT ' + @constraint exec sp_executesql @sql fetch next from cur into @schema, @tbl, @constraint end close cur deallocate cur
No comments:
Post a Comment