SQL Server 修改表结构

一、创建表

--直接定义主外键
create table wallet(
    ID varchar(36) primary key,
    Money decimal(18,2) not null,
    Name varchar(36) default '余额',
    Member_ID varchar(36) foreign key references Member(ID) unique
)
--或最后定义主外键
create table wallets(
    ID varchar(36),
    Money decimal(18,2) not null,
    Name varchar(36) default '余额',
    Member_ID varchar(36) unique,
    primary key(ID),
    foreign key(Member_ID) references Member(ID),
    check(Money > -1),
)

二、修改表结构

1. 添加字段

--alter table 表名 add 字段名 数据类型
alter table wallet add CreateTime date

2. 修改字段名称/表名称

exec sp_rename '表名.旧字段名','新字段命';

3. 修改字段类型

--alter table 表名 alter column 字段名 数据类型
alter table wallet alter column Money decimal(15,2)

三、修改约束

 1. 添加/修改约束

--修改表字段不能为空
alter table wallet alter column createtime date not null
--添加约束表字段必须唯一
alter table wallet add unique(createtime) 
--添加主键约束
alter table wallet add primary key(ID)
--添加外键
alter table wallet add foreign key(Member_ID) references Member(ID)
--添加自定义约束
alter table wallet add check(money != 0)
--添加或修改字段的默认值
alter table wallet add  default(getdate()) for createtime

其中check、foreign key、primary key、unique,使用constraint关键字为约束命名例如:

alter table wallet add constraint names_unique unique(createtime) 

约束的名称为names_unique

2. 删除约束

--alter table 表名 drop constraint 约束名称
alter table wallet drop constraint names_unique
--取消默认值:设置默认值null并且设置该字段允许为null
alter table wallet alter column createtime date null
alter table wallet add  default(null) for createtime

猜你喜欢

转载自www.cnblogs.com/haosit/p/8874416.html