使用SQL语句,可以轻松修改SQL主键,下面就将为您介绍这种修改SQL主键的方法,供您参考,希望对您学习修改SQL主键方面有所启迪。
- declare @defname varchar(100)
- declare @cmd varchar(500)
- declare @tablename varchar(100)
- declare @keyname varchar(100)
- Set @tablename='Temp1'
- Set @keyname='id' --需要設置的key,分隔
- select @defname= name
- FROM sysobjects so
- JOIN sysconstraints sc
- ON so.id = sc.constid
- WHERE object_name(so.parent_obj) = @tablename
- and xtype='PK'
- if @defname is not null
- begin
- select @cmd='alter table '+ @tablename+ ' drop constraint '+ @defname
- --print @cmd
- exec (@cmd)
- end
- else
- set @defname='PK_'+@keyname
- select @cmd='alter table '+ @tablename+ ' ADD constraint '+ @defname +' PRIMARY KEY CLUSTERED('+@keyname+')'
- exec (@cmd)
【编辑推荐】