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)

4. 设置自动增长可输入

因为自动增长无法取消,除非采用重新建表再把数据同步过来的方法。所以设置该表自动增长字段为可以用insert的语句手动输入

--set IDENTITY_INSERT 表名 on
set IDENTITY_INSERT wallet on

三、修改约束

 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

转载于:https://www.cnblogs.com/haosit/p/8874416.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值