其他分享
首页 > 其他分享> > 修改表之ALTER TABLE

修改表之ALTER TABLE

作者:互联网

--创建表
IF OBJECT_ID('Department','U') IS NOT NULL DROP TABLE Department
CREATE TABLE Department
(
	DepartmentID smallint IDENTITY(1,1) NOT NULL,
	Name	NVARCHAR(20)	NOT NULL,
	GroupName 	NVARCHAR(20) NOT NULL,
	CONSTRAINT PK_Department_DepartmentID PRIMARY KEY(DepartmentID)
);

--插入两条记录
INSERT INTO Department(Name,GroupName) VALUES('A','帅哥');
INSERT INTO Department(Name,GroupName) VALUES('B','美女');

--查询记录
SELECT * FROM Department

结果:

 

A:插入新列

ALTER TABLE Department--添加列
	ADD DepartmentIDnew smallint  NULL

--修改列DepartmentIDnew的值
UPDATE Department SET DepartmentIDnew=DepartmentID

B:删除主键列

--删除列需要先删除其约束
ALTER TABLE Department
	DROP CONSTRAINT PK_Department_DepartmentID--删除主键


--删除列
ALTER TABLE Department
	DROP COLUMN DepartmentID

结果:主键列已经被删除

 

C:给列增加约束

--修改列定义
ALTER TABLE Department
	ALTER COLUMN DepartmentIDnew smallint NOT NULL


--给列添加约束(这里是增加主键)
ALTER TABLE Department
	ADD CONSTRAINT PK_Department_DepartmentIDnew 
		PRIMARY KEY(DepartmentIDnew)

 

D:启用或禁用约束

--添加CHECK约束
ALTER TABLE Department
	ADD CONSTRAINT CK_Department_DepartmentID
		CHECK(DepartmentIDnew>=1)


--禁用CHECK约束
ALTER TABLE Department
NOCHECK CONSTRAINT CK_DePARTMENT_DepartmentID

--启用CHECK约束
ALTER TABLE Department
CHECK CONSTRAINT CK_Department_DepartmentID

 

标签:DepartmentIDnew,表之,DepartmentID,Department,TABLE,NULL,ALTER
来源: https://blog.csdn.net/ilovetheworld/article/details/94741938