SQL Server 如何添加删除外键、主键,以及更新自增属性
1.添加删除主键和外键
例如:
-----删除主键约束
DECLARE @NAME SYSNAME
DECLARE @TB_NAME SYSNAME
SET @TB_NAME = 'Date'
SELECT TOP 1 @NAME=NAME FROM SYS.OBJECTS WITH(NOLOCK)
WHERE TYPE_DESC ='PRIMARY_KEY_CONSTRAINT' AND PARENT_OBJECT_ID = (
SELECT OBJECT_ID
FROM SYS.OBJECTS WITH(NOLOCK)
WHERE NAME = @TB_NAME )
SELECT @NAME as PK
DECLARE @ALTERSQL NVARCHAR(MAX)
SET @ALTERSQL=N'ALTER TABLE '+@TB_NAME+'
DROP CONSTRAINT '+@NAME+''
EXEC SP_EXECUTESQL @ALTERSQL
----添加主键约束
alter table Date add constraint PK_Date primary key(ID)
----设置外键约束的SQL语句:
alter table student add constraint FK_student_classes foreign key(cla_id) references classes(ID)
----删除外键约束
alter table student drop constraint FK_student_classes
2.自增属性的更新
------如果仅仅是指定值插入,可用以下语句,临时取消
SET IDENTITY_INSERT classes ON
INSERT INTO classes (ID,Name) VALUES(7,'测试1')
SET IDENTITY_INSERT [classes] OFF
-----新增一列,删除自增列,修改列名
alter table classes add ID_Temp int
update a set ID_Temp=ID
alter table classes drop column ID
exec sp_rename 'ID_Temp', 'ID', 'column'
--------通过修改系统关于该表的列属性,该方法使用不当将可能引起其它不可预料的错误(未操作成功)
sp_configure 'allow update',1
reconfigure with override
go
update syscolumns set colstat=0 where colstat=1 and id=object_id('tablename')
go
sp_configure 'allow update',0
reconfigure with override