【SQL Server】(二)DDL--create、drop、alter
SQL对大小写不敏感
一、CREATE
1、create database
create database xinrong;
2、create table
1)数据类型
整数:integer()、int()-可以不指定大小、smallint()、tinyint() 参数是最大位数
小数:decimal()、numeric() 参数1是最大位数,参数2是小数位数
字符串:char()、varchar()-必须给出大小 参数是字符串的长度
日期:date()
2)SQL约束(6 个)
(1)NOT NULL(一种写法)
create table course( cid int not null, cname varchar(255), tid int );
(2)UNIQUE(三种写法)
create table course( cid int not null, cname varchar(255) not null unique, tid int, unique(cid), CONSTRAINT uc_courseID unique(cid, tid) --命名多列约束 );
(3)PRIMART KEY(三种写法)
create table course( cid int primary key, cname varchar(255), tid int, --注意:如果前面有列已经定义了primary key,就不能定义下面这两种主键了 --primary key(cid) --CONSTRAINT pk_courseID primary key(cid, tid) );
(4)FOREIGN KEY(三种写法)
create table course( cid int, cname varchar(255), tid int foreign key references teacher(tid), foreign key(tid) references teacher(tid), --CONSTRAINT fk_courseID foreign key(t_id) references teacher(t_id) );
(5)CHECK(三种写法)
create table course( cid int CHECK(cid > 0), cname varchar(255), tid int, CHECK(tid > 0), CONSTRAINT chk_course CHECK(cid > 0 AND tid > 0) );
(6)DEFAULT(一种写法)
create table course( cid int , cname varchar(255) DEFAULT 'Renne', tid int, time date DEFAULT GETDATE() --插入系统值 );
3)自增--IDENTITY
IDENTITY 的开始值是1,每条新记录递增1。
create table student( id int PRIMARY KEY IDENTITY, name varchar(255) )
3、create index
create [UNIQUE] INDEX student_index on student(id [DESC], name);
4、select into 创建表
select * into student4 from student;
二、ALTER
1、增加/修改 表约束
1)UNIQUE(两种写法)
alter table Persons add unique(id_p); alter table Persons add constraint uc_PersonID unique(id_p, lastname);
2)PRIMARY KEY(两种写法)
--注:如果使用ALTER TABLE 语句添加主键,必须把主键列声明为不包含NULL 值(在表首次创建时)。
alter table Persons add primary key(id_p); alter table Persons add constraint uc_PersonID primary key(id_p, lastname);
3)FOREIGN KEY(两种写法)
alter table Orders add FOREIGN KEY(Id_P) REFERENCES Person(Id_P); alter table Orders add CONSTRAINT fk_PerOrders FOREIGN KEY(Id_P) REFERENCES Persons(Id_P);
4)CHECK(两种写法)
alter table Persons add CHECK(Id_P > 0); alter table Persons add CONSTRAINT chk_Persons CHECK(Id_P > 0 AND City = 'Sandnes');
5)DEFAULT(一种写法)
alter table Persons alter COLUMN city set DEFAULT 'Renne';
2、撤销表约束
需要之前有约束的命名,就是之前得是使用 CONSTRAINT 定义约束
1)UNIQUE、PRIMARY KEY、FOREIGN KEY、CHECK(一种写法)
alter table Persons drop constraint 约束名;
2)DEFAULT(一种写法)
alter table Persons alter COLUMN City DROP DEFAULT;
3、添加列
alter table student add col_add int; --add 要加的列名类型
三、DROP
1、撤销索引
drop index student.index_id; --接的是table_name.index_name
2、删除表
drop table student;
3、删除数据库
drop database XinrongDatabase;
4、清空表数据
truncate table student;
5、删除列
alter table student drop column name;
浙公网安备 33010602011771号