SQL Server 的数据表简单操作

时间:2024-03-25 12:03:44

--创建数据表--
[use 要创建数据表的数据库名称
go]
create table 要创建的表名
(
字段名 数据类型[长度] [null | not null] [primary key],
... ... ... ... ,
字段名 数据类型[长度] [null | not null]
)

例:
use 商品管理数据库
go
create table 客户信息表
(
客户编号 nchar(8) not null,
客户姓名 nvarchar(5) not null,
联系电话 nvarchar(11) not null,
地址 nvarchar(30) null,
邮箱 nvarchar(20)
)

--修改数据表--
[use 要修改数据表的数据库名称
go]
alter table 要修改的表名
alter column 要修改字段名[修改后的数据类型[(长度)] [null | not null ] ]--修改字段
[add 字段名 数据类型[(长度)] [null | not null ] ]--添加新字段
[drop column 字段名]--删除字段

例:
use 商品管理数据库
go
alter table 客户信息表
alter column 邮箱 varchar(50) null
go

--删除数据表--
[use 要删除数据表的数据库名称
go]
drop table 表名[,表名,...] --删除数据表,同时删除数据表中所有数据,以及该表与数据库中其他表的关联和约束

--数据表的约束设置--
--设置主键约束(PK)--
[use 要设置数据表字段主键的数据库名称
go]
alter table 数据表名
add constraint 约束名 --添加约束
primary key(字段名 [,字段名...]) --设置主键的字段名

例:
use 商品管理数据库
go
alter table 客户信息表
add constraint PK_客户信息表_客户编号
primary key(客户编号)

--设置默认约束(DF)--
alter table 数据表名
add constraint 约束名
default 默认值 for 字段名

例:
use 商品管理数据库
go
alter table 客户信息表
add constraint DF_客户信息表_地址
default '辽宁沈阳' for 地址

--设置唯一约束(UN)--
[use 要设置数据表字段主键的数据库名称
go]
alter table 数据表名
add constraint 约束名 --添加约束
unique [clustered | nonclustered](字段名 [,字段名...]) --clustered | nonclustere表示聚集或非聚集

例:
use 商品管理数据库
go
alter table 客户信息表
add constraint UN_客户信息表_邮箱
unique clustered(邮箱)

--设置检查约束(CK)--
[use 要设置数据表字段主键的数据库名称
go]
alter table 数据表名
add constraint 约束名 --添加约束
check (约束表达式)

例:
use 商品管理数据库
go
alter table 客户信息表
add constraint CK_客户信息表_邮箱
check (邮箱 like '_%@_%._%')

--设置外键约束(FK)--
[use 要设置数据表字段主键的数据库名称
go]
alter table 数据表名
add constraint 约束名 --添加约束
foreign key (字段名) --foreign key指定添加约束为外键约束
references 主表名(字段名)

例:
use 商品管理数据库
go
alter table 商品信息表
add constraint FK_商品类型表_商品信息表_商品类型编号
foreign key (商品类型编号)
references 商品类型表(商品类型编号)

--查看约束--
exec sp_help 约束名 --显示Name(名称)、Owner(所有者)、Type(类型)、Create_datetime(时间),一般是默认约束和检查约束
exec sp_helptext 约束名 --显示约束表达式,一般是默认约束和检查约束

例:
exec sp_help CK_客户信息表_邮箱
exec sp_helptext CK_客户信息表_邮箱

--删除约束--
alter table 要删除约束的数据表名
drop constraint 约束名[, 约束名, ...] --要删除的约束名

例:
alter table 商品信息表
drop constraint DF_商品信息表_地址

注:"--"可看成说明或者注释文本