数据库SQL语句的操作
SQLServer数据库的基础知识的回顾:
1)主数据文件:*.mdf
2)次要数据文件:*.ndf
3)日志文件:*.ldf
每个数据库至少要包含两个文件:一个数据文件和一个日志文件
如何查看SQL Server的帮助==================快捷键F1
一、创建文件夹
exec sp_configure 'show advanced options',1
go
reconfigure
go
exec sp_configure 'xp_cmdshell',1
go
reconfigure
go
exec xp_cmdshell 'mkdir E:\新建文件'
go
二、创建数据库
1.例子:
--判断,如果有这个数据库则进行删除
if exists(select * from sysdatabases where name='MySchool')
begin
drop database MySchool
end
--创建数据库
create database MySchool
on primary
(
--数据文件的具体描述
name='MySchool_data', --主数据文件的逻辑名称+++++++必须写
filename='E:\MySchool_data.mdf', --主数据文件的物理名称+++++++必须写
size=5mb, --主数据文件的初始大小
maxsize=100mb, --主数据文件增长的最大值
filegrowth=15% --主数据文件的增长率
)
log on
(
--日志文件的具体描述,各参数含义同上
name='MySchool_log',
filename='E:\MySchool_log.ldf',
size=2mb,
filegrowth=1mb
)
go
三、创建表
2 use MySchool --将当前数据库设置为MySchool,以便在MySchool里创建表
3 go
4 --判断是否存在表,存在则删除
5 if exists (select * from sysobjects where name='Student')
6 drop table Student
7---创建Student表
8 create table Student
9 (
10 StudentNo int identity(1,1) primary key not null, --学号 自增 主键,非空
11 loginpwd nvarchar(20) not null,
12 StudentName nvarchar(20) not null,
13 Sex bit default'女' not null, --性别,取值0,1
14 GradeId int not null,
15 Phone nvarchar(50) null,
16 Address nvarchar(100) null,
17 BornDate datetime not null,
18 Email nvarchar(20) null,
19 IdentityCard varchar(18) not null
20 )
21 go
四、创建约束
语法:
1 alter table 表名
2 add constraint 约束名 约束类型 具体的约束说明
例子:
1、添加默认约束(默认'地址不详')
1 alter table Student
2 add constraint df_address default('地址不详') for address
2、添加检查约束(要求出生在1996年10月26日)
1 alter table Student
2 add constraint ck_BornDate check (BornDate >='1996-10-26')
3、添加唯一约束(身份证全世界只有一个)
1 alter table Student
2 add constraint uq_IdentityCard unique (IdentityCard)
4、添加主键约束
1 alter table Student
2 add constraint pk_StudentNo primary key(StudentNo)
5、添加外键约束(主表 Student 和从表 REsult建立关系,关联列StudentNo)
1 alter table Result
2 add constraint fk_StudentNo
3 foreign key(StudentNo) references Student (StudentNo)
五、sql操作数据库数据的实现(增、删、查、改)
(一)插入数据
语法:
insert into 目标表(新表)
select '列名' union
eg
insert into card(ID,password)
select ‘0023-ABC’,‘ABC’ union
(二)增加数据
语法:
insert into 表名
values (‘ ’,‘ ’)
eg
insert into card
values (‘0023-ABC’,‘ABC’)
(三)修改数据
语法:
update 表名 set 行名
where 列名
eg
update card set password=‘pwd’
where ID=‘0023-ABE’
(四)删除数据
语法:
delete from 表名
where 行名
eg
delete from card
where ID=‘0023-ABE’
(五)查看数据
语法:
select * from 表名
eg
select * from student
浙公网安备 33010602011771号