【Sql Server学习】Sql Server基础第一篇

* 创建数据库MyDb */

create database MyDb
on
(
       name=MyDb_data,
       filename='d:\sql\MyDb_data.mdf',
       size=3,
       maxsize=4,
       filegrowth=1
)
log on
(
       name=MyDb_log,
       filename='d:\sql\MyDb_data.ldf',
       size=1,
       maxsize=2,
       filegrowth=1
)

/*选择MyDb数据库*/

use MyDb
GO

/* 查看所有的数据库 */

sp_databases
GO

/* 查看所有的数据库 */

select * from sysdatabases
go


/*在数据库MyDb中创建student表*/

use MyDb
go
create table student
(
       sno char(9) primary key,
       sname char(6) not null,
       ssex char(2) default ('男'),
       sage int,
       sdept varchar(10)
)

/*显示所有的表,包含系统表*/

sp_tables;

/*在MyDb数据库中创建course表*/

create table course
(
       cno varchar(3) primarykey,
       cname varchar(12),
       cpno varchar(3),
       ccredit int
)


/*在MyDb数据库中创建sc表,并且与student和sc外联*/

create table sc
(
       sno char(9) not null,
       cno varchar(3) not null,
       grade int,
       primary key(sno,cno),
       foreign key (sno)references student (sno) on delete cascade on update cascade,
       foreign key (cno)references course (cno) on delete cascade on update cascade
)


/*在student表添加Telephone列,11长度的char*/

alter table student
add Telephone char(11)


/*更改student表的Sdept列为16个长度的varchar*/

alter table student
alter column sdept varchar(16)


/*sc表的成绩grade列建立约束,要求在0到100范围*/

alter table sc
add constraint ck_grade check (grade>=0 and grade <= 100)


/*student表的学好sno列建立约束,学号必须由9位阿拉伯数字组成*/

alter table student
add constraint ck_sno check (sno like '[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]')


/*删除sc表在grade列上的check约束,约束名位ck_grade*/

alter table sc
drop ck_grade


/*删除Telephone属性列*/

alter table student
drop column Telephone


/*student表的ssex列增加默认值约束,设置默认值位'男'默认值的约束名字位Stu_sex_default */

alter table student
add constraint Stu_sex_defalut default ('男') for ssex


/*向student表中插入两条记录*/

insert into student values ('220021510','李勇','男',20,'ls');
insert into student values ('200215125','tom','女',19,'cs');
select * from student;
go
 


/*修改student表中的记录*/

update student set sdept='cs' where sname='李勇';
select *from student;


/*删除李勇记录*/

delete from student where sname='李勇'
select *from student;
go


 

整理下实验报告,以防以后需要用的时候忘了

你可能感兴趣的:(【Sql Server学习】Sql Server基础第一篇)