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

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

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

declare @TableName nvarchar(250)
--声明读取数据库所有数据表名称游标mycursor1
declare mycursor1 cursor for select name from dbo.SysObjects WHERE OBJECTPROPERTY(ID, 'ISUSErTable') = 1
 --打开游标
open mycursor1
--从游标里取出数据赋值到我们刚才声明的数据表名变量中
fetch next from mycursor1 into @TableName
--如果游标执行成功 
while (@@fetch_status=0)
begin 
 --定义当前主键约束变量
declare @ConstraintName varchar (200)

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

--声明读取数据表所有主键约束名称游标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

相关推荐