代碼實現數據庫的創建和查詢(隨便寫點,只為記錄自己的成長過程)


第一本書快要學完了,時間過得飛快!

  這是這前三章學到的,自己來總結下!

一.設計數據庫的步驟

  1.收集信息  2.標識實體  3.標識每個實體需要存儲的詳細信息 4.標識實體之間的關系

  

  三大范式;

  1.第一范式:確保每列的原子性

  2.第二范式:在第一范式的基礎上,確保表中的每列都和主鍵相關

  3.第三范式:在滿足第二范式的基礎上,確保除主鍵列直接相關,而不是間接相關

 

  E-R圖:

  矩形代表實體   菱形代表關系   橢圓代表屬性

  

  Entity:實體  normal:正常的  model:模型  selationship:關系 state:狀態  promation:提升

  formate:格式化 diagram:圖表 guest:客人 hotel:旅館

二.

 

 1.創建數據庫

  Use master

  If exists(select * from sysdatabases where name=’MySchool’)

  Drop database MySchool

  Create database MySchool

  go

  (

   Name=’MySchool_data’ , ---邏輯文件名

   Filename=’D:\新建文件夾\MySchool_data.mdf ’ ,  ---物理文件名

   Size=5,

   Filegrowth=10,

   Maxsize=50

 

  )

  Log on

  (

  Name=’MySchool_log’,

  Filename=’D:\新建文件夾\MySchool_log.ldf’,

  Size:5,

  Filegrowth=15%,

  Maxsize=50

  )

  Go

  2.創建表

  Use MySchool

  If exists(select * from sysubjects where name=’student’)

  Drop table student

  Create table student

  (

   Stuid int indentity(1,1) not null,

 Stuname varcchar(20) not null,

 Sex char(1) not null,

 Stuage int not null,

 Grade int not null,

 Address varchar(255) null,

 Phone varchar(50) null,

 IdentityCrad varchar(18) not null,

BornDate datetime not null

 )

 Go

 3.創建約束

  (1)主鍵約束

      Alter table student

      Add constraint pk_stuid primary key (stuid)

  (2)檢查約束

      Alter table student

      Add constraint ck_BornDate check(BornDate>=’1980-01-01’)

  (3)默認約束

      Alter table studnet

      Add constraint df_address default(‘地址不詳’) for Address

  (4)唯一約束

     Alter table student

     Add constraint uq_IdentutyCrad unique(IdentityCrad)

  (5)外鍵約束

Alter table result

Add constraint fk_stuid

Foregin key(stuid) references student(stuid)

 4.刪除表,刪除約束,刪除數據庫

   Drop table 表名

   Drop database 數據庫名

   Alter table 表名

   Drop constraint 約束名

Create:創造 drop:刪除 primary:主要的 exists:存在 alter:改變 growth:增長 constrint:約束

Unique:唯一 foregin:外鍵 references:引用

use master
go
if exists(select * from sysdatabases where name='Library')
drop database Library

 

create database Library
on primary
(
name='Library',
filename='D:\project\Library.mdf',
size=5,
filegrowth=15%
)
log on
(
name='Library_log',
filename='D:\project\Library_log.ldf',
size=1,
filegrowth=15%
)
go

 

use Library  --先將數據庫定位到Library
go
if exists(select * from sysobjects where name='Book')
drop table Book
create table Book  /*--創建圖書信息表*/
(
BID varchar(10)  primary key not null,
BName varchar(20) not null,
Author varchar(20) null,
PubComp varchar(20) null,
PubDate datetime not null,
BCount int not null,
Price money not null
)
go

 


use Library  --先將數據庫定位到Library
go
alter table Book  --必須以ISBN開頭
add constraint ck_BID check(BID like 'ISBN%')
go

 

use Library  --先將數據庫定位到Library
go
alter table Book  --檢查出版日期是否小於當前日期
add constraint ck_PubDate check(PubDate<=getdate())
go

 

use Library  --先將數據庫定位到Library
go
alter table Book  --現存數量必須大於等於1
add constraint ck_BCount check (BCount>=1)
go

 

use Library  --先將數據庫定位到Library
go
alter table Book
add constraint ck_Price check (Price>0)
go

 

use Library  --先將數據庫定位到Library
go 
--檢查是否有讀者信息表
if exists(select * from sysobjects where name='Reader')
drop table Reader
create table Reader /*--讀者信息表*/
(
RID varchar(10) primary key not null,
RName varchar(10) not null,
LendNum int not null,
RAddress varchar(50) null
)
go

 

use Library  --先將數據庫定位到Library
go
alter table Reader
add constraint ck_LendNum check (LendNum>=0)
go

 


use Library  --先將數據庫定位到Library
go
if exists (select * from sysobjects where name='Borrow')
drop table Borrow
create table Borrow /*創建圖書借閱表*/
(
RID varchar(10) not null,
BID varchar(10) not null,
LendDate datetime not null,primary key(RID,BID,LendDate),
WillDate datetime null,
ReturnDate datetime null
)
go

 

 

/*--添加外鍵約束--*/
alter table Borrow
add constraint fk_RID
foreign key (RID) references Reader(RID)
go

 

/*--添加外鍵約束--*/

 

alter table Borrow
add constraint fk_BID
foreign key (BID) references Book(BID)
go

 

 

/*--添加默認約束--*/
alter table Borrow
add constraint df_LendDate default('getdate()') for LendDate
go

 

/*--添加檢查約束--*/

 

alter table Borrow
add constraint ck_WillDate check (WillDate>=LendDate) 
go

/*--添加默認約束--*/

 

alter table Borrow
add constraint df_WillDate default (dateadd(mm,1,getdate())) for WillDate
go

 

use Library  --先將數據庫定位到Library
go
if exists (select * from sysobjects where name='Penalty')
drop table Penalty
create table Penalty  /*創建罰款記錄表*/
(
RID varchar(10) not null,
BID varchar(10) not null,
PDate datetime not null,primary key(RID,BID,PDate),
PType int not null,
Amount money not null
)
go

 

/*--添加外鍵約束--*/

alter table Penalty
add constraint fk1_RID
foreign key(RID) references Reader(RID)
go

 

/*--添加外鍵約束--*/
alter table Penalty
add constraint fk1_BID
foreign key(BID) references Book(BID)
go

 

/*--添加默認約束--*/
alter table Penalty
add constraint df_PDate default('getdate()') for PDate
go

 

/*--添加檢查約束--*/

 

alter table Penalty
add constraint ck_PType check (Ptype=1 or Ptype=2  or Ptype=3 ) 
go

 

/*--添加檢查約束--*/

 

alter table Penalty
add constraint ck_Amount check (Amount>0) 
go

 

/*--添加一列--*/
alter table Book add BTotal int

 

三.局部變量和全局變量

   1.局部變量

    局部變量的名稱必須以@作為前綴

    局部變量的聲明語法:

    Declare  @variable_name DataType

    variable_name:局部變量的名稱

    DateType:局部變量的數據類型

    例:

        Declare  @name varchar(32)  --聲明一個存放姓名的變量 name

        Declare  @number int       --聲明一個存放學號的變量 number

    給局部變量賦值有兩種方法:

    Set  @variable_name=value

    Select  @variable_name=value

    Set 和 select 的區別:

    Set只能支持一個變量的賦值

    Seelct 能同時支持多個變量的賦值

 

2.全局變量

  全局變量是以@@前綴命名的

  全局變量都是系統定義的,不能自己命名

  @@servicename  :本地服務器的名稱

  @@error : 最后一個T-SQL錯誤的錯誤號

  @@rowcount: 上一個SQL語句受影響的行數

  @@version: SQL Server的版本信息

3.數字轉換為字符串

  Cast(@variable_name as 數據類型)

 

  Convert(數據類型,@variable)

  Cast()函數和convert()函數用於將某種數據類型的表達式轉換為另一種數據類型的表                            

      達式。與cast()函數不同的是,在將日期時間類型/浮點類型轉換為字符串數據時,示

      conver()函數可以通過第三個參數指定轉換后的字符樣式,不同的樣式使轉換后的數

      據的顯示格式不同。

4. Begin-end語句

      Begin

          語句或者語句塊

      End

 

      If-else條件語句

      If

       語句或者語句塊1  

      Else

        語句或者語句塊2

     

      當有多條語句時,則需要與begin-end結合使用

       If

        Begin

         語句1

         語句2

        end

       Else

     Begin

      語句

     end

 

  While(條件)

Begin

 語句或者語句塊

 [Break][continue]

End

 

Case多分支語句

 語法:

   Case

     When 條件1  then 結果1

     When 條件2  then 結果2

     Else[ 其他結果 ]

   End

 

Go指令:它是一條或多條SQL語句的集合

 

use master
go
if exists(select * from sysdatabases where name='MySchool')
drop table MySchool
create database MySchool
on
(
name='MySchool',
filename='D:\project\MySchool.mdf',
size=10,
filegrowth=20%
)
log on
(
name='MySchool_log',
filename='D:\project\MySchool_log.ldf',
size=3,
filegrowth=1,
maxsize=20
)
go

 

use MySchool
go
if exists(select * from sysobjects where name='Subject')
drop table Subject
create table Subject /*創建科目表*/
(
SubjectNo int identity(1,1) not null,
SubjectName nvarchar(50) ,
ClassHour int ,
GradeID int not null

 

)
go

 


use MySchool 
go
if exists(select * from sysobjects where name='Result')
drop table Result
create table Result /*創建成績表*/
(
StudentNo int not null,
SubjectNo int not null,
ExamDate datetime not null,
StudentResult int  not null

 

)
go

 

use MySchool 
go
if exists(select * from sysobjects where name='Student')
drop table Student
create table Student /*創建學生表*/
(
StudentNo int not null,
LoginPwd nvarchar(50) not null,
StudentName nvarchar(50) not null,
Sex bit not null,
GradeID int not null,
Phone varchar(50),
Address nvarchar(255) ,
BornDate datetime not null,
Email varchar(50),
IdentityCard varchar(18)

 

)
go

 

use MySchool 
go
if exists(select * from sysobjects where name='Grade')
drop table Grade
create table Grade /*創建年級表*/
(
GradeID int identity(1,1) not null,
GradeName nvarchar(50) not null

 

)
go

 

---年級表添加主鍵約束
alter table Grade
add constraint pk_GradeID primary key (GradeID)
go 

 

---學生表添加主鍵約束
alter table Student 
add constraint pk_StudentNo primary key (StudentNo)
go

 


--學生表添加唯一約束
alter table Student
add constraint uq_IdentityCard unique (IdentityCard)
go

 

--學生表添加默認約束
alter table Student
add constraint df_Address default ('地址不詳') for Address
go

 

--學生表添加檢查約束
alter table Student
add constraint ck_BornDate check(BornDate>='1980-01-01')
go

 

--學生表添加外鍵約束
alter table Student
add constraint fk_GradeID
foreign key(GradeID) references Grade(GradeID)
go

 

insert into Subject( SubjectName, ClassHour, GradeID)values
('s1',150,1),
('s2',180,2),
('y2',200,3)

 

--科目表添加主鍵約束
alter table Subject
add constraint pk_SubjectNo primary key(SubjectNo)
go

 

--科目表添加檢查約束
alter table Subject
add constraint ck_ClassHour check(ClassHour>=0)
go

 

--科目表添加外鍵約束
alter table Subject
add constraint fk1_GradeID
foreign key(GradeID) references Grade(GradeID)
go

 


--成績表添加主鍵約束
alter table Result
add constraint pk1_StudentNo
primary key (StudentNo,SubjectNo,ExamDate)
go

 


--成績表添加默認約束
alter table Result
add constraint df_ExamDate default(getdate()) for ExamDate
go

 

--成績表添加檢查約束
alter table Result
add constraint ck_StudentResult check (StudentResult<=100 or StudentResult>=0)
go

 


--成績表添加外鍵約束
alter table Result
add constraint fk_StudentNo
foreign key(StudentNo) references Student(StudentNo)
go

 

--添加外鍵約束
alter table Result
add constraint fk2_SubjectNo
foreign key(SubjectNo) references Subject(SubjectNo)
go

 

--
alter table Result
drop constraint ck_StudentResult

 

alter table Result
alter column StudentResult decimal (5,2)

 

alter table Result
add constraint ck_StudentResult check (StudentResult<=100 or StudentResult>=0)
go

 

第三章.


----打印直角三角形

declare @num varchar(20),@count int
select @num='',@count=0
while(@count<5)
begin 
 select @num+='*',@count+=1
 print  @num
end


----面試表
use myschool
create table  biao
(
 riqi varchar(20) not null,
 jieguo varchar(10) not null
)

insert into biao values('2010-05-06','')
insert into biao values('2010-05-06','')
insert into biao values('2010-05-06','')
insert into biao values('2010-05-06','')
insert into biao values('2012-05-06','')
insert into biao values('2012-05-06','')
insert into biao values('2012-05-06','')

select * from biao

select riqi as 日期,sum
(
case when jieguo='' then 1
else 0
end
) 
as 勝,sum
(
case when jieguo='' then 1
else 0
end
)
asfrom biao
group by riqi


select * from student

 

declare @name varchar(20)
select @name=studentname from student 
where studentno=23270
print @name

declare @age int
select @age=DATEDIFF(YY,birthday,GETDATE()) from student
where studentno=23270
print @age


----九九乘法表
declare @n int ,@m int ,@u varchar(255)
select @n=1
while(@n<10)
begin
select @u='',@m=1
while(@m<=@n)
begin
select @u=@u+cast(@m as nvarchar)+'*'+cast(@n as nvarchar)+'='+CAST(@m*@n as nvarchar)+' ', @m=@m+1
0end
print @u
set @n=@n+1  
end


--上機練習3
select * from result

declare @date datetime
select @date=MAX(examdate) from result where studentno=23231
declare @score int
select @score=studentResult from result where studentno=23231 and examdate=@date print @score
if(@score>85)
begin
 print '優秀'
end
else if(@score>70)
begin
 print '良好'
end
else if(@score>60)
begin
 print '中等'
end
else 
begin
 print ''
end


--上機練習4

--查詢科目編號
declare @subid int 
select @subid=subjectid from subject where subjectname='oop' 
--查詢最近的考試時間
declare @date datetime
select @date =MAX(examdate) from result where subjectid=@subid  order by examdate

--查詢有沒有考試不及格的同學
declare @count int
select @count=COUNT(1) from result  where studentresult<60 and subjectid=@subid and examdate=@date
while(@count>0)
begin
 update result set studentresult=studentresult+2 where studentresult<95 and subjectid=@subid and examdate=@date
 --加分后,再判定有沒有及格的
 select @count=COUNT(1) from result  where studentresult<70 and subjectid=@subid and examdate=@date 
end

print @count


select * from result

 


--上機練習5
create table Admins
(
admin varchar(20)  primary key  not null,
pwd varchar(10) not null
)
go
 
 insert into Admins values('張三','1'),
 ('李四','11')
 
 declare @count int 
 select @count=COUNT(1) from Admins where admin='張三'
 if(@count>0)
 begin
  update Admins set pwd='111' where admin='張三'  
 end
 
 print @count

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM