SQL创建数据库

本文介绍了使用SQL进行数据库创建、切换、删除以及表的创建和删除操作。内容包括设置当前数据库为系统数据库,判断数据库是否存在,创建和删除数据库的步骤,以及在新建数据库中创建表并添加约束条件的方法,同时讨论了如何删除表。
摘要由CSDN通过智能技术生成

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

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值