sql server DDL语句 建立数据库 定义表 修改字段等

列即字段
行即记录

一、数据库:

1.建立数据库

create database 数据库名;
use 数据库名;

create database exp1;
use exp1;

mysql同样

2.删除数据库

drop database 数据库名;
drop database exp1;

mysql同样

 

二、表:

1.创建表

create table 表名(
    列名1 类型1 [约束],
    列名2 类型2 [约束],
    ...
);

create table Student(
    Sno Char(7) primary key,--学号  
    Sname Char(10) not null,--学生姓名
    Ssex Char(2) not null,--性别
    Sage Smallint,--年龄
    Clno Char(5) not null--学生所在班级号
);

mysql同样

2.删除表

drop table 表名;

drop table test;

mysql同样  不过都尽量少写 威力太大

3.修改表

3.1修改表名

exec sp_rename '旧表名','新表名'

exec sp_rename 'test', 'test1'

mysql不一样

alter table 旧表名 rename to 新表名;

alter table user1 rename to user10;

3.2添加字段

alter table 表名 add 字段名 字段描述;

alter table Student add Birthday Datetime;

mysql一样

3.3删除字段

alter table 表名 drop column 字段名;--必须加column 不加指的是删除约束

alter table Student drop column Class;

mysql不一样 不用加column

alter table 表名 drop 字段名;

alter table user drop pwd;

3.4修改字段名

sp_rename '表名.旧字段名','新字段名'

sp_rename 'Student.Class','clazz';

mysql不一样

alter table 表名 change 字段名称 新字段描述; -- 可以顺便改描述

alter table user change password pwd varchar(10);

3.5修改字段描述

alter table 表名 alter column 字段名 新描述

alter table Student alter column Class char(10);

mysql不一样

alter table 表名 modify 字段名称 字段类型 [约束];

alter table user modify pwd int;  -- 不能改名称 只能改描述

三、索引

1.添加索引

create [unique] [clustered] index 索引名 on 表名(字段名 [asc],字段名名 [desc]);  --asc升序  desc降序   默认升序

create unique index Stusno on Student(Sno);--student表按学号升序建立唯一索引

create unique index SCno on Cj(Sno asc,Cno desc);--Cj表按学号升序 课程号降序建立唯一索引

create clustered index CjGde on Cj(Grade desc);--建立聚簇索引  (聚集索引)

-- sql server可视化工具建索引 类型改成索引即可  建立聚簇索引将‘创建为聚集的’改为‘是’即可

2.重命名索引

exec sp_rename '表名.索引名','新索引名'

exec sp_rename 'Student.Stusno','Stuno'; 

3.删除索引

drop index 表名.索引名

drop index Student.Stuno;

以上为自己的笔记,也可以参考https://www.cnblogs.com/yuzhonghua/p/7612594.html

猜你喜欢

转载自blog.csdn.net/hza419763578/article/details/83040061