SQL創建數據庫

SQL創建數據庫以及表的基本語法:

設置當前數據庫爲系統數據庫

use master
go

判斷數據庫是否已經存在,如果已存在就刪除

if exists(select * from sysdatabases where name='student')
drop database student
go

創建數據庫

create database student
on primary
(
	name="student",
	filename="D:\student.mdf",
	size=5mb,
	filegrowth=3mb,
	maxsize=100mb
)
log on
(
	name="student_log.ldf",
	filename="D:\student.ldf",
	size=3mb,
	filegrowth=10%,
	maxsize=100mb
)
go

創建表之前  把數據庫切換成新建的數據庫

use student
go

創建表,創建表的同時直接添加約束條件

create table stuInfo
(
	stuId int primary key not null,
	stuName varchar(50),
	stuSex varchar(2) default('男'),
	stuAge int check(stuAge>0 and stuAge<150),
	stuAddr varchar(200),
	stuPid int identity(1,1)
)
go
create table stuMarks
(
	stuId int references stuInfo(stuId),
	sub varchar(50),
	score int
)
go

刪除表

drop table stuInfo
go

刪除數據庫

drop database student
go

只創建表,限制條件後面添加

create table stuInfo
(
	stuId int not null,
	stuName varchar(50),
	stuSex varchar(2),
	stuAge int,
	stuAddr varchar(200),
	stuPid varchar(18),
	stuSid int
)
go
create table stuMarks
(
	stuId int,
	sub varchar(50),
	score int
)
go
--設置主鍵
alter table stuInfo
add constraint PK_stuId primary key(stuId)
--設置唯一約束
alter table stuInfo
add constraint UQ_stuPid unique(stuPid)
--check約束
alter table stuInfo
add constraint CK_stuAge check(stuAge>0 and stuAge<150)
--檢查約束
alter table stuInfo
add constraint DF_stuSex default('男') for stuSex
--外鍵約束
alter table stuMarks
add constraint FK_stuId foreign key(stuId) references stuInfo(stuId)
--刪除約束條件
alter table stuInfo
drop constraint DF_stuSex

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章