學習 SQL Server (5) :視圖,索引,事務和鎖+T_SQL

  • 2020 年 6 月 19 日
  • 筆記

–=============== 視圖的創建 =================、

–create view 視圖名 as 查詢語句
–注意:視圖查詢中的字段不能重名
— 視圖中的數據是『假數據』,真實數據在數據表中,如果數據表中被修改了,則視圖中的數據也受影響
— 使用視圖和使用數據表方法一樣。視圖也可排序、分組、設置條件,還可以嵌套

create view edu_view
as
select s1.Id 學生編號,s1.Name 學生姓名,s2.Score 分數,c.Name 課程名稱,t.Name 教師姓名 from Students s1 join Scores s2 on s2.StudentId=s1.Id join Course c on s2.CourseId=c.Id join Teachers t on t.Id=c.TeacherId
select * from edu_view

–修改視圖
–alter view 視圖名 as 查詢語句
alter view edu_view
as
select s1.Id 學生編號,s1.Name 學生姓名,s2.Score 分數,c.Name 課程名稱,t.Name 教師姓名 from Students s1
join Scores s2 on s2.StudentId=s1.Id
join Course c on s2.CourseId=c.Id
join Teachers t on t.Id=c.TeacherId
where t.Name=’耿冰冰’
select * from edu_view

–刪除視圖
— drop view edu_view

–查看視圖信息
exec sp_help students

 

–========================== 索引 ===============================

–索引的創建

–創建非聚集索引
— create index 索引名 on 表名(字段名)
create index index_age on students(Age)

–create unique [clustered] / [nonclustered] 【聚集】 / 【非聚集】
–index 索引名稱 on 表名(列名 asc/desc)
–with fillfator =98 【填充因子,填充比例】

create unique clustered index index_age1 on Students(age) with fillfactor=90

–刪除索引
–drop index 表名.索引名
drop index students.index_age

–修改索引
–exec sp_rename ‘表名.現有名稱’,’新名稱’
exec sp_rename ‘students.index_age1′,’newindex_age’

–查看 索引
exec sp_helpindex ‘students’

 

 

— ================ 事務 transaction / tran ============和鎖=======
select * from Students

begin tran
insert into Students values(‘學生小明’,33,1)
insert into Students values(‘學生小李’,34,1)
insert into Students values(‘學生小紅’,35,1)
insert into Students values(‘學生小黑’,36,1)

declare @num int –定義int類型變量
set @num=(select count(1) from Students) —給變量@num賦值 num的值就是數據表中的行數
if @num>=9
begin
rollback tran –回滾事務
end
else
begin
commit tran –提交事務
end

–========= 鎖的大小分類
–鎖按照鎖定的數據的範圍的大小,分為庫所、表鎖、頁鎖、行鎖

–創建第一個事務
begin tran
update Students set Name=’沙雕’ where Id=1023
–設置鎖定時間
waitfor delay ’00:00:09′
commit tran

–創建第二個事務

 

 

 

–====================  T_SQL =====================

use Unit11
—————————————————————–
–判斷學生表人數是男生多還是女生多

declare @count1 int –定義整形變量 存儲男生人數
declare @count0 int –定義整形變量 存儲女生人數

set @count1=(select count(1) from Students where Sex=1) –通過查詢給變量@count1賦值
select @count0=(select count(1) from Students where Sex=0)

if @count1>@count0
begin
print ‘男生多’
end
else
begin
print ‘女生多’
end
—————————————————————–

———————————輸出1-100之間的偶數——————————-
declare @n int
set @n=1
while @n<=100
begin
if @n%2=0
begin
print @n
end
set @n=@n+1
end
———————————————————————————–

–全局變量 @@變量名
–局部變量名 @變量名

select @@ERROR

select datediff(day,getdate(),’2020-1-1′)
select datediff(day,’2000-9-14′,getdate())
select datediff(hour,’2000-9-14′,getdate())

 

作者還在學習中,發現錯誤的請在評論區留言。  如果有客友覺得文章還行的話,請點波推薦哦👍。 謝謝你們!!