zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    idea报“Usage of API documented as @since 1.7”这一问题的解决方法
    分页的总页数算法
    Error evaluating expression 'category.id != null and category.id != '''. Cause: org.apache.ibatis.og
    json日期处理类
    解决maven过滤必需配置文件的方法
    数据库配置文件
    springmvc 提供的统一解决json中文乱码配置
    EXPLAIN 命令详解
    MySQL索引与Index Condition Pushdown(二)
    【MySQL】性能优化之 Index Condition Pushdown
  • 原文地址:https://www.cnblogs.com/haosit/p/8874416.html
Copyright © 2011-2022 走看看