SQL删除数据库中所有用户数据表主键

2014-11-24 18:25:08 · 作者: · 浏览: 0

--SQL删除数据库中所有用户数据表主键


--查询删除前的当前数据库所有约束
select * from information_schema.key_column_usage


--删除当前数据表的所有主键约束


--声明读取数据表所有主键约束名称游标mycursor2
declare mycursor2 cursor for select name from dbo.sysobjects where Xtype = 'PK' and Parent_Obj = (select [ID] from dbo.sysobjects where id = object_id(N'['+@TableName+']') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
--打开游标
open mycursor2
--从游标里取出数据赋值到主键约束名称变量中
fetch next from mycursor2 into @ConstraintName
--如果游标执行成功
while (@@fetch_status=0)
begin
--删除当前找到的主键
exec ('ALTER TABLE ['+@TableName+'] DROP CONSTRAINT ['+@ConstraintName+']')
--print 'ALTER TABLE ['+@TableName+'] DROP CONSTRAINT ['+@ConstraintName+']'
--用游标去取下一条记录
fetch next from mycursor2 into @ConstraintName
end


--关闭游标
close mycursor2
--撤销游标
deallocate mycursor2


--用游标去取下一条记录
fetch next from mycursor1 into @TableName
end


--关闭游标
close mycursor1
--撤销游标
deallocate mycursor1


--查询删除后的当前数据库所有约束
select * from information_schema.key_column_usage