mysql複習筆記

閱讀目錄

1.什麼是SQL語句
2.使用sql語句建立數據庫和表
3.建立數據表
4.數據完整性約束
5.四中基本字符類型說明
6.SQL基本語句
7.類型轉換函數
8.日期函數
9.數學函數
10.字符串函數
11.聯合結果集union
12.CASE函數用法
13.IF ELSE語法
14.WHILE循環語法
15.子查詢
16.錶鏈接Join
17.事務
18.視圖
19.觸發器
20.存儲過程
21.分頁存儲過程
22.索引
23.臨時表html


1.什麼是SQL語句正則表達式

sql語言:結構化的查詢語言。(Structured Query Language),是關係數據庫管理系統的標準語言。sql

它是一種解釋語言:寫一句執行一句,不須要總體編譯執行。shell

語法特色:數據庫

1.沒有「 」,字符串使用‘ ’包含
2.沒有邏輯相等,賦值和邏輯相等都是=
3.類型再也不是最嚴格的。任何數據均可以包含在‘ ’之內
4.沒有bool值的概念,可是在視圖中能夠輸入true/false
5.它也有關係運算符:> < >= <= = <> != ,它返回一個bool值
6.它也有邏輯運算符: !(not) &&(and) ||(or)
7.它不區別大小寫c#

2.使用sql語句建立數據庫和表數組

語法:服務器

create database 數據庫名稱 on primary --默認在主文件組上 ( name='邏輯名稱_data' , --當你發現它不是一句完整的sql語句,而僅僅是一個處理結構中的某一句的時候,就須要添加 , size=初始大小,--數值不包含在‘’之內 filegrowth=文件增加 , maxsize=最大容量, filename='物理路徑' ) log on ( name='邏輯名稱_log' , --當你發現它不是一句完整的sql語句,而僅僅是一個處理結構中的某一句的時候,就須要添加 , size=初始大小,--數值不包含在‘’之內 filegrowth=文件增加 , maxsize=最大容量, --通常來講日誌文件不限制最大容量 filename='物理路徑' )
--判斷數據庫文件是否已經存在 :數據庫的記錄都存儲在master庫中的sysdatabases表中 --自動切換當前數據庫 --使用代碼開啓外圍應該配置器 exec sp_configure 'show advanced options' ,1 RECONFIGURE exec sp_configure 'xp_cmdshell',1 RECONFIGURE --自定義目錄 xp_cmdshell能夠建立出目錄 'mkdir f:\project':指定建立目錄 exec xp_cmdshell 'mkdir f:\project' use master --exists 函數判斷()中的查詢語句是否返回結果集,若是返回告終果集則獲得true,不然獲得false if exists( select * from sysdatabases where name='School') drop database School --刪除當前指定名稱的數據庫 create database School on primary ( name='School_data',--邏輯名稱.說明最多可以存儲100mb數據,若是沒有限制就能夠將硬盤存儲滿 size=3mb,--初始大小 maxsize=100mb,--最大容量 filegrowth=10%,--文件增加一次增加10% filename='f:\project\School_data.mdf' ), --建立文件組 filegroup mygroup ( name='School_data1',--邏輯名稱.說明最多可以存儲100mb數據,若是沒有限制就能夠將硬盤存儲滿 size=3mb,--初始大小 maxsize=100mb,--最大容量 filegrowth=10%,--文件增加一次增加10% filename='F:\qiyi\School_data1.ndf' ) log on ( name='School_log',--邏輯名稱 size=3mb,--初始大小 --maxsize=100mb,--最大容量 filegrowth=10%,--文件增加一次增加10% filename='f:\project\School_log.ldf' ), ( name='School_log1',--邏輯名稱 size=3mb,--初始大小 --maxsize=100mb,--最大容量 filegrowth=10%,--文件增加一次增加10% filename='F:\qiyi\School_log1.ldf' )

3.建立數據表框架

語法:ide

create table 表名 ( 字段名稱 字段類型 字段特徵(是否爲null,默認值 標識列 主鍵 惟一鍵 外鍵 check約束), 字段名稱 字段類型 字段特徵(是否爲null,默認值 標識列 主鍵 惟一鍵 外鍵 check約束) ) 建立老師表Teacher :IdNameGenderAgeSalaryBirthday
use School if exists(select * from sysobjects where name='Classes') drop table Classes create table Classes ( Classid int identity(1,1), ClassName nvarchar(50) not null ) if exists(select * from sysobjects where name='teacher') drop table teacher create table Teacher ( Id int identity(1,1),--能夠同時建立多個特徵,用空格 分隔開。 identity是標識列,第一個參數是種子,第二個是增量 Name nvarchar(50) not null,-- not null標記它的值不能爲null--不能不填寫 ClassId int not null, Gender bit not null, Age int , Salary money, --若是不標記爲 not null.那麼就至關於標記了null Birthday datetime )

4.數據完整性約束

實體完整性:實體就是指一條記錄。這種完整性就是爲了保證每一條記錄不是重複記錄。是有意義的

  • 主鍵:非空和惟一.一個表只有一個主鍵,可是一個主鍵能夠是由多個字段組成的 組合鍵
  • 標識列:系統自動生成,永遠不重複
  • 惟一鍵:惟一,可是能夠爲null,只能null一次

域完整性:域就是指字段,它是爲了保證字段的值是準和有效,合理值

  • 類型 是否null,默認值,check約束,關係

自定義完整性:

  • check約束 , 存儲過程 觸發器

引用完整性:一個表的某個字段的值是引用自另一個表的某個字段的值。引用的表就是外鍵表,被引用的表就是主鍵表

  • 1.創建引用的字段類型必須一致
  • 2.創建引用的字段的意義同樣
  • 3.創建主外鍵關係的時候選擇 外鍵表 去創建主外鍵關係
  • 4.創建主外鍵關係的字段在主表中必須是主鍵或者惟一鍵
  • 5.對於操做的影響
    ①.在添加數據時,先添加主鍵表再添加外鍵表數據
    ②.在刪除的時候先外鍵表數據再刪除主鍵表數據

  • 級聯的操做:不建議使用:會破壞數據完整性
  • 不執行任何操做:該報錯就報錯,該刪除就刪除
  • 級聯:刪除主表記錄,從表引用該值的記錄也被刪除
  • 設置null:刪除主表記錄,從表對應的字段值設置爲null,前提是能夠爲null
  • 設置爲default:刪除主表記錄,從表對應的字段值設置爲default,前提是能夠爲default

主鍵約束(PK Primary key)惟一鍵約束(UQ unique) 外鍵約束(FK foreign key) 默認值約束(DF default) check約束(CK check)

語法:

alter table 表名 add constraint 前綴_約束名稱 約束類型 約束說明(字段 關係表達式 值)
use School if exists(select * from sysobjects where name='PK_Classes_Classid') alter table classes drop constraint PK_Classes_Classid alter table classes add constraint PK_Classes_Classid primary key(classid) --爲id添加主鍵 alter table teacher add constraint PK_teacher_id primary key(id) --爲name添加惟一鍵 alter table teacher add constraint UQ_Teacher_Name unique(Name) --同時建立salary的默認約束和agecheck約束 alter table teacher add constraint DF_Teacher_Salary default(5000) for salary, constraint CK_Teacher_Age check(age>0 and age<=100) --爲teacher表的classid字段建立主外鍵 if exists(select * from sysobjects where name='FK_Teacher_Classes_Classid') alter table teacher drop constraint FK_Teacher_Classes_Classid alter table teacher with nocheck --不檢查現有數據 add constraint FK_Teacher_Classes_Classid foreign key(classid) references classes(classid) --on delete set default 級聯操做 --不執行任何操做:該報錯就報錯,該刪除就刪除 --no action --默認選擇 --級聯:刪除主表記錄,從表引用該值的記錄也被刪除 --cascade --設置null:刪除主表記錄,從表對應的字段值設置爲null,前提是能夠爲null --set null --設置爲default:刪除主表記錄,從表對應的字段值設置爲default,前提是能夠爲default --set default

5.四中基本字符類型說明

--len(參數) --獲取指定參數內容的字符個數 select LEN('abcd') 4】運行結果 select LEN('中華人民共和國') 7 --DataLength(參數):獲取指定內佔據的字節數--空間大小 select DataLength('abcd') 4 select DataLength('中華人民共和國') 14 --char類型:當空間分配後,不會由於存儲的內容比分配的空間小就回收分配的空間。可是若是存儲的內容超出了指定的空間大小,就會報錯,當你存儲的內容的長度變化區間不大的時候能夠考慮使用char select LEN(char) from CharTest 2 select DataLength(char) from CharTest 10 --varchar var--變化的:當你存儲的內容小於分配的空間的時候,多餘的空間會自動收縮。可是若是存儲的內容超出了指定的空間大小,就會報錯 當存儲的內容波動區間比較大時候使用varchar select LEN(varchar) from CharTest 2 select DataLength(varchar) from CharTest 2 --nchar-- n表明它是一個unicode字符。規定無論什麼樣的字符都佔據兩個字節。 char:空間是固定的 select LEN(nchar) from CharTest 10 select DataLength(nchar) from CharTest 20 --nvarchar n var char select LEN(nvarchar) from CharTest 2 select DataLength(nvarchar) from CharTest 4

圖片描述

6.SQL基本語句

數據插入

調用方法 一 一對應原則:類型對應,數量對應,順序對應。

語法: 形參 實參

insert into 表名([字段列表]) values(值列表) --數據必需要符合數據完整性 插入操做是單個表的操做 插入操做insert一次只能插入一條記錄
use School --插入teacher全部字段的數據.若是在表後沒有指定須要插入的字段名稱,那麼就默認爲全部字段添加值 --可是必定須要注意的是:標識列永遠不能自定義值--不能人爲插入值 --僅當使用了列列表而且 IDENTITY_INSERT  ON 時,才能爲表'Teacher'中的標識列指定顯式值。 insert into Teacher values('張三',5,1,30,4000,'1984-9-11') insert into Teacher(Name,ClassId,Gender,Age,Salary,Birthday) values('張三',5,1,30,4000,'1984-9-11') --不爲能夠爲null的字段插入值 :能夠null的字段能夠不賦值 --列名或所提供值的數目與表定義不匹配 insert into Teacher(Name,ClassId,Gender,Age,Salary) values('李四',5,1,30,4000) --非空字段必定須要賦值 :不能將值 NULL 插入列 'Gender',表 'School.dbo.Teacher';列不容許有 Null 值。INSERT 失敗 insert into Teacher(Name,ClassId,Age,Salary) values('李四',5,30,4000) --爲有默認值的字段插入值: --1.不寫這一列讓系統自動賦值 insert into Teacher(Name,ClassId,Gender,Age) values('王五',5,1,30) --指定 null或者default insert into Teacher(Name,ClassId,Gender,Age,Salary,Birthday) values('趙六',5,1,30,default,null) --數據必須徹底符合表的完整性約束 insert into Teacher(Name,ClassId,Gender,Age,Salary,Birthday) values('趙六1',5,1,300,default,null) --任意類型的數據均可以包含在''之內, 不包括關鍵字 insert into Teacher(Name,ClassId,Gender,Age,Salary,Birthday) values('馬鵬飛','5','0','15',default,null) --可是字符串值若是沒有包含在''之內.會報錯 列名 '蘭鵬' 無效。 insert into Teacher(Name,ClassId,Gender,Age,Salary,Birthday) values('蘭鵬','5','0','15',default,null) --可是數值組成的字符串能夠不使用''包含 insert into Teacher(Name,ClassId,Gender,Age,Salary,Birthday) values(123,'5','0','15',default,null) --日期值必須包含在’‘之內,不然就是默認值 insert into Teacher(Name,ClassId,Gender,Age,Salary,Birthday) values('鄒元標2','5','0','15',default,'1991-9-11')

數據刪除

語法:

delete [from] 表名 where 條件
delete from Teacher where Age<20 --特色: --1.刪除是一條一條進行刪除的 --2.每一條記錄的刪除都須要將操做寫入到日誌文件中 --3.標識列不會從種子值從新計算,以從上次最後一條標識列值往下計算 --4.這種刪除能夠觸發delete觸發器 --truncate table 表名 --沒有條件,它是一次性刪除全部數據 --特色: --1.一次性刪除全部數據,沒有條件,那麼日誌文件只以最小化的數據寫入 --2.它可使用標識列從種子值從新計算 --3.它不能觸發delete觸發器 truncate table teacher

數據更新(數據修改):必定須要考慮是否有條件

語法:

update 表名 set 字段=值,字段=值 。。where 條件
update Teacher set Gender='true' --修改時添加條件 update Teacher set Gender=0 where Id=20 --多字段修改 update Teacher set ClassId=4,Age+=5,Salary=5000 where Id=22 --修改班級id=4,同時年齡》20歲的人員工資+500 update Teacher set Salary=Salary+500 where ClassId=4 and Age>20

數據檢索--查詢

語法: *表明全部字段

select */字段名稱列表 from 表列表
select StudentNo,StudentName,Sex,[Address] from Student --能夠爲標題設置 別名,別名能夠是中文別名 select StudentNo as 學號,StudentName 姓名,性別=Sex,[Address] from Student --添加常量列 select StudentNo as 學號,StudentName 姓名,性別=Sex,[Address] ,國籍='中華人民共和國' from Student
--select的做用 --1.查詢 --2.輸出 select 1+1 --+是運算符,系統會自動爲你作類型轉換 select 1+'1' select '1'+1 --若是+兩邊都是字符串,那麼它就是一字符串鏈接符 select '1'+'1' select 'a'+1 --能夠輸出多列值 select 1,2,34,3,545,67,567,6,7 --TopDistinct select * from Student --top能夠獲取指定的記錄數,值能夠大於總記錄數.可是不能是負值 select top 100 * from Student --百分比是取ceiling() select top 10 percent * from Student --重複記錄與原始的數據表數據無關,只與你查詢的結果集有關係 distinct能夠去除結果集中的重複記錄--結果集中每一列的值都同樣 select distinct LoginPwd,Sex,Email from Student select distinct Sex from Student select的做用
--聚合函數: --1.null過濾 --2.都須要有一個參數 --3.都是返回一個數值 --sum():求和:只能對數值而言,對字符串和日期無效 --avg():求平均值 --count():計數:獲得知足條件的記錄數 --max():求最大值:能夠對任意類型的數據進行聚合,若是是字符串就比較拼音字母進行排序 --min():求最小值 --獲取學員總人數 select COUNT(*) from Student --查詢最大年齡值 select MIN(BornDate) from Student select max(BornDate) from Student --查詢總分 select SUM(StudentResult) from Result where StudentNo=2 --平均分 select avg(StudentResult) from Result where SubjectId=1 --注意細節: select SUM(StudentName) from Student select SUM(BornDate) from Student select min(StudentName) from Student select max(StudentName) from Student --查詢學號,姓名,性別,年齡,電話,地址 ---查詢女生 select StudentNo,StudentName,Sex,BornDate,Address from Student where Sex='女' and BornDate >'1990-1-1' and Address='廣州傳智播客' --指定區間範圍 select StudentNo,StudentName,Sex,BornDate,Address from Student where BornDate >='1990-1-1' and BornDate<='1993-1-1' --between...and >= <= select StudentNo,StudentName,Sex,BornDate,Address from Student where BornDate between '1990-1-1' and '1993-1-1' --查詢班級id 1 3 5 7的學員信息 select * from Student where ClassId=1 or ClassId=3 or ClassId=5 or ClassId=7 --指定具體的取值範圍--能夠是任意類型的範圍.值的類型須要一致--能夠相互轉換 select * from Student where ClassId in(1,3,'5',7) select * from Student where ClassId not in(1,3,'5',7) 聚合函數
--帶條件的查詢-模糊查詢-- 只針對字符串而言 --查詢   的女生信息 --=是一種精確查詢,須要徹底匹配 select * from Student where Sex='女' and StudentName='林' --通配符--元字符 --%:任意個任意字段 window:* 正則表達式 :.* --_:任意的單個字符 --[]:表明一個指定的範圍,範圍能夠是連續也能夠是間斷的。與正則表達式徹底同樣[0-9a-zA-Z].能夠從這個範圍中取一個字符 --[^]:取反值 select * from Student where Sex='女' and StudentName='林%' --通配符必須在模糊查詢關鍵的中才能夠作爲通配符使用,不然就是普通字符 --like  。。。。同樣 select * from Student where Sex='女' and StudentName like '林%' select * from Student where Sex='女' and StudentName like '林_' --[]的使用 學號在11~15之間的學員信息 select * from Student where StudentNo like '[13579]' ---處理null --null:不是地址沒有分配,而是不知道你須要存儲什麼值 因此null是指 不知道。可是=只能匹配具體的值,而null根本就不是一個值 select COUNT(email) from Student where Email !=null select COUNT(email) from Student where Email is null select count(email) from Student where Email is not null --將null值替換爲指定的字符串值 select StudentName,ISNULL(Email,'沒有填寫電子郵箱') from Student where ClassId=2 模糊查詢
--當你看到 每個,,各自,不一樣,,分別 須要考慮分組 --查詢每個班級的男生人數 --與聚合函數一塊兒出如今查詢中的列,要麼也被聚合,要麼被分組 select classid,Sex,COUNT(*) from Student where Sex='男' group by ClassId,sex --查詢每個班級的總人數,顯示人數>=2的信息 --1.聚合不該出如今 WHERE 子句中--語法錯誤 select ClassId ,COUNT(*) as num from Student where Email is not null GROUP by ClassId having COUNT(*)>=2 order by num desc --完整的sql查詢家庭 --5 1 2 3 4 6 --select 字段列表 from 表列表 where 數據源作篩選 group by 分組字段列表 having 分組結果集作篩選 Order by 對結果集作記錄重排 select ClassId ,COUNT(*) as num from Student where Email is not null GROUP by ClassId order by ClassId desc --關於top的執行順序 排序以後再取top select top 1 ClassId ,COUNT(*) as num from Student GROUP by ClassId order by num desc 分組統計

7.類型轉換函數

--select :輸出爲結果集--虛擬表 --print:以文本形式輸出 只能輸出一個字符串值. print 1+'a' select 1,2 select * from Student --類型轉換 --Convert(目標類型,源數據,[格式]) --日期有格式 print '個人成績是:'+convert(char(3),100) print '今天是個大日子:'+convert(varchar(30),getdate(),120) select getdate() select len(getdate()) --cast(源數據 as 目標類型) 它沒有格式 print '個人成績是:'+cast(100 as char(3))

8.日期函數

--getdate():獲取當前服務器日期 select GETDATE() --能夠在源日期值是追加指定時間間隔的日期數 select DATEADD(dd,-90,GETDATE()) --dateDiff:找到兩個日期之間指定格式的差別值 select StudentName,DATEDIFF(yyyy,getdate(),BornDate) as age from Student order by age --DATENAME:能夠獲取日期的指定格式的字符串表現形式 select DATENAME(dw,getdate()) --DATEPART:能夠獲取指定的日期部分 select cast(DATEPART(yyyy,getdate()) as CHAR(4))+'-' +cast(DATEPART(mm,getdate()) as CHAR(2))+'-' +cast(DATEPART(dd,getdate()) as CHAR(2))

9.數學函數

--rand:隨機數:返回01之間的數,理論上說能夠返回0可是不能返回1 select RAND() --abs:absolute:取絕對值 select ABS(-100) --ceiling:獲取比當前數大的最小整數 select CEILING(1.00) --floor:獲取比當前數小的最大整數 select floor(1.99999) power: select POWER(3,4) --round():四捨五入.只關注指定位數後一位 select ROUND(1.549,1) --sign:正數==1 負數 ==-1 0=0 select SIGN(-100) select ceiling(17*1.0/5)

10.字符串函數

--1.CHARINDEX --IndexOf():可以返回一個字符串在源字符串的起始位置。找不到就返回0,若是能夠找到就返回從1開始的索引--沒有數組的概念 --第一個參數是指須要查詢的字符串,第二個是源字符串,第三個參數是指從源字符的那個索引位置開始查找 select CHARINDEX('人民','中華人民共和國人民',4) --LEN():能夠返回指定字符串的字符個數 select LEN('中華人民共和國') --UPPER():小寫字母轉換爲大寫字母 LOWER():大寫轉小寫 select LOWER(UPPER('sadfasdfa')) --LTRIM:去除左空格 RTIRM:去除右空格 select lTRIM(RTRIM(' sdfsd '))+'a' --RIGHT:能夠從字符串右邊開始截取指定位數的字符串 若是數值走出範圍,不會報錯,只會返回全部字符串值,可是不能是負值 select RIGHT('中華人民共和國',40) select LEFT('中華人民共和國',2) --SUBSTRING() select SUBSTRING('中華人民共和國',3,2) --REPLACE 第一個參數是源字符串,第二個參數是須要替換的字符串,第三個參數是須要替換爲何 select REPLACE('中華人民共和國','人民','居民') select REPLACE('中 華 人民 共 和 國',' ','') --STUFF:將源字符串中從第幾個開始,一共幾個字符串替換爲指定的字符串 select STUFF('中華人民共和國',3,2,'你懂的') --sudyfsagfyas@12fasdf6.fsadfdsaf declare @email varchar(50)='sudyfsagfyas@12fasdf6.fsadfdsaf' select CHARINDEX('@',@email) select LEFT(@email,CHARINDEX('@',@email)-1) --使用right select right(@email,len(@email)-CHARINDEX('@',@email)) --使用substring select SUBSTRING(@email,CHARINDEX('@',@email)+1,LEN(@email)) --使用stuff select STUFF(@email,1,CHARINDEX('@',@email),'')

11.聯合結果集union

--聯合結果集union select * from Student where Sex='男' --union select * from Student where Sex='女' --聯合的前提是: --1.列的數量須要一致:使用 UNIONINTERSECT  EXCEPT 運算符合並的全部查詢必須在其目標列表中有相同數目的表達式 --2.列的類型須要能夠相互轉換 select StudentName,Sex from Student --在字符串排序的時候,空格是最小的,排列在最前面 union select cast(ClassId as CHAR(3)),classname from grade --unionunion all的區別 --union是去除重複記錄的 --union all不去除重複 :效率更高,由於不須要判斷記錄是否重複,也沒有必須在結果庥是執行去除重複記錄的操做。可是能夠須要消耗更多的內存存儲空間 select * from Student where ClassId=2 union all select * from Student where ClassId=2 --查詢office這科目的全體學員的成績,同時在最後顯示它的平均分,最高分,最低分 select ' '+cast(StudentNo as CHAR(3)),cast(SubjectId as CHAR(2)),StudentResult from Result where SubjectId=1 union select '1','平均分',AVG(StudentResult) from Result where SubjectId=1 union select '1','最高分',max(StudentResult) from Result where SubjectId=1 union select '1','最低分',min(StudentResult) from Result where SubjectId=1 --一次性插入多條數據 --1.先將數據複製到另一個新表中,刪除源數據表,再將新表的數據插入到源數據表中 --1.select */字段 into 新表 from 源表 --1.新表是系統自動生成的,不能人爲建立,若是新表名稱已經存在就報錯 --2.新表的表結構與查詢語句所獲取的列一致,可是列的屬性消失,只保留非空和標識列。其它所有消失,如主鍵,惟一鍵,關係,約束,默認值 select * into newGrade from grade truncate table grade select * from newGrade --select * into grade from newGrade --2.insert into 目標表 select 字段列表/* from 數據源表 --1、目標表必須先存在,若是沒有就報錯 --2.查詢的數據必須符合目標表的數據完整性 --3.查詢的數據列的數量和類型必須的目標的列的數量和對象徹底對應 insert into grade select classname from newGrade delete from admin --使用union一次性插入多條記錄 --insert into 表(字段列表) --select 值。。。。 用戶自定義數據 --union --select  。。。。 insert into Admin select 'a','a' union all select 'a','a' union all select 'a','a' union all select 'a',null

12.CASE函數用法

至關於switch case---c#中的switch...case只能作等值判斷
這能夠對字段值或者表達式進行判斷,返回一個用戶自定義的值,它會生成一個新列。
2.要求then後面數據的類型一致
1.第一種作等值判斷的case..end

case 字段或者表達式 when .值..then .自定義值 when .值..then .自定義值 ..... else 若是不知足上面全部的when就知足這個else end
--顯示具體班級的名稱 select StudentNo,StudentName, case ClassId --若是case後面接有表達式或者字段,那麼這種結構就只能作等值判斷,真的至關於switch..case when 1 then '一班' when 2 then '2班' when 3 then '3班' when null then 'aa' --不能判斷null else '搞不清白' end, sex from Student --2.作範圍判斷,至關於if..else,它能夠作null值判斷 --case --若是沒有表達式或者字段就可實現範圍判斷 -- when 表達式 then  --不要求表達式對同一字段進行判斷 -- when 表達式 then  -- ..... --else 其它狀況 --end select StudentNo,StudentName, case when BornDate>'2000-1-1' then '小屁孩' when BornDate>'1990-1-1' then '小青年' when BornDate>'1980-1-1' then '青年' --when Sex='女' then '是女的' when BornDate is null then '出生不詳' else '中年' end from Student --百分制轉換爲素質教育 90 -A 80--B 70 --C 60 --D <60 E NULL--沒有參加考試 select StudentNo,SubjectId, case when StudentResult>=90 then 'A' when StudentResult>=80 then 'B' when StudentResult>=70 then 'C' when StudentResult>=60 then 'D' when StudentResult is null then '沒有參加考試' else 'E' end 成績, ExamDate from Result

13.IF ELSE語法

1.沒有{},使用begin..end.若是後面只有一句,能夠不使用begin..end包含
2.沒有bool值,只能使用關係運算符表達式
3.也能夠嵌套和多重
4.if後面的()能夠省略

declare @subjectname nvarchar(50)='office' --科目名稱 declare @subjectId int=(select Subjectid from Subject where SubjectName=@subjectname) --科目ID declare @avg int --平均分 set @avg=(select AVG(StudentResult) from Result where SubjectId=@subjectId and StudentResult is not null) --獲取平均分 print @avg if @avg>=60 begin print '成績不錯,輸出前三名:' select top 3 * from Result where SubjectId=@subjectId order by StudentResult desc end else begin print '成績很差,輸出後三名:' select top 3 * from Result where SubjectId=@subjectId order by StudentResult end

14.WHILE循環語法

1.沒有{},使用begin..end
2.沒有bool值,須要使用條件表達式
3.能夠嵌套
4.也可使用break,continue

go declare @subjectName nvarchar(50)='office' --科目名稱 declare @subjectId int--科目ID declare @classid int =(select classid from Subject where SubjectName=@subjectName) --查詢當前科目屬於那一個班級 set @subjectId=(select SubjectId from Subject where SubjectName=@subjectName) --獲取科目ID declare @totalCount int --總人數 :那一個班級須要考試這一科目 set @totalCount=(select COUNT(*) from Student where ClassId=@classid) print @totalcount --14 declare @unpassNum int --不及格人數 set @unpassNum=(select COUNT(distinct Studentno) from Result where SubjectId=@subjectId and StudentNo in(select StudentNo from Student where ClassId=@classid) and StudentResult<60) while(@unpassNum>@totalCount/2) begin --執行循環加分 update Result set StudentResult+=2 where SubjectId=@subjectId and StudentNo in(select StudentNo from Student where ClassId=@classid) and StudentResult<=98 --從新計算不及格人數 set @unpassNum=(select COUNT(distinct Studentno) from Result where SubjectId=@subjectId and StudentNo in(select StudentNo from Student where ClassId=@classid) and StudentResult<60) end go declare @subjectName nvarchar(50)='office' --科目名稱 declare @subjectId int--科目ID declare @classid int =(select classid from Subject where SubjectName=@subjectName) --查詢當前科目屬於那一個班級 set @subjectId=(select SubjectId from Subject where SubjectName=@subjectName) --獲取科目ID declare @totalCount int --總人數 set @totalCount=(select COUNT(*) from Student where ClassId=@classid) print @totalcount --14 declare @unpassNum int --不及格人數 while(1=1) begin set @unpassNum=(select COUNT(distinct Studentno) from Result where SubjectId=@subjectId and StudentNo in(select StudentNo from Student where ClassId=@classid) and StudentResult<60) if(@unpassNum>@totalCount/2) update Result set StudentResult+=2 where SubjectId=@subjectId and StudentNo in(select StudentNo from Student where ClassId=@classid) and StudentResult<=98 else break end

15.子查詢

子查詢:一個查詢中包含另一個查詢。被包含的查詢就稱爲子查詢,包含它的查詢就稱父查詢。
1.子查詢的使用方式:使用()包含子查詢
2.子查詢分類:

  • 獨立子查詢:子查詢能夠直接獨立運行.
    查詢比「王八」年齡大的學員信息
select * from Student where BornDate<(select BornDate from Student where StudentName='王八')
  • 相關子查詢:子查詢使用了父查詢中的結果
--子查詢的三種使用方式 --1.子查詢作爲條件,子查詢接在關係運算符後面 > < >= <= = <> !=,若是是接這關係運算符後面,必須保證 子查詢只返回一個值 --查詢六期班的學員信息 select * from Student where ClassId=(select ClassId from grade where classname='八期班') --子查詢返回的值不止一個。當子查詢跟隨在 =、!=、<、<=、>、>= 以後,或子查詢用做表達式時,這種狀況是不容許的。 select * from Student where ClassId=(select ClassId from grade) --查詢八期班之外的學員信息 --當子查詢返回多個值(多行一列),可使用in來指定這個範圍 select * from Student where ClassId in(select ClassId from grade where classname<>'八期班') --當沒有用 EXISTS 引入子查詢時,在選擇列表中只能指定一個表達式。若是是多行多列或者一行多列就須要使用exists --使用 EXISTS 關鍵字引入子查詢後,子查詢的做用就至關於進行存在測試。外部查詢的 WHERE 子句測試子查詢返回的行是否存在 select * from Student where EXISTS(select * from grade) select * from Student where ClassId in(select * from grade) --2.子查詢作爲結果集-- select top 5 * from Student --前五條 --使用top分頁 select top 5 * from Student where StudentNo not in(select top 5 studentno from Student) --使用函數分頁 ROW_NUMBER() over(order by studentno),能夠生成行號,排序的緣由是由於不一樣的排序方式獲取的記錄順序不同 select ROW_NUMBER() over(order by studentno),* from Student --查詢擁有新生成行號的結果集 注意:1.子查詢必須的別名 2.必須爲子查詢中全部字段命名,也就意味着須要爲新生成的行號列命名 select * from (select ROW_NUMBER() over(order by studentno) id,* from Student) temp where temp.id>0 and temp.id<=5 select * from (select ROW_NUMBER() over(order by studentno) id,* from Student) temp where temp.id>5 and temp.id<=10 select * from (select ROW_NUMBER() over(order by studentno) id,* from Student) temp where temp.id>10 and temp.id<=15 --3.子查詢還能夠作爲列的值 select (select studentname from student where studentno=result.studentno),(select subjectname from subject where subjectid=result.SubjectId), StudentResult from Result --使用Row_number over()實現分頁 --1.先寫出有行號的結果集 select ROW_NUMBER() over(order by studentno),* from Student --2.查詢有行號的結果集 子查詢作爲結果集必須添加別名,子查詢的列必須都有名稱 select * from (select ROW_NUMBER() over(order by studentno) id,* from Student) temp where id>0 and id<=5 --查詢年齡比「廖楊」大的學員,顯示這些學員的信息 select * from Student where BornDate<(select BornDate from Student where StudentName='廖楊') --查詢二期班開設的課程 select * from Subject where ClassId=(select ClassId from grade where classname='二期班') --查詢參加最近一次「office」考試成績最高分和最低分 --1查詢出科目 ID select subjectid fromSubjectwhereSubjectName='office'--2.查詢出這一科目的考試日期select MAX(ExamDate)fromResultwhereSubjectId=(select subjectid fromSubjectwhereSubjectName='office')--3,寫出查詢的框架select MAX(StudentResult),MIN(StudentResult)fromResultwhereSubjectId=()andExamDate=()--4.使用子查詢作爲條件select MAX(StudentResult),MIN(StudentResult)fromResultwhereSubjectId=(select subjectid fromSubjectwhereSubjectName='office')andExamDate=(select MAX(ExamDate)fromResultwhereSubjectId=(select subjectid fromSubjectwhereSubjectName='office'))

16.錶鏈接Join

--1.inner join :可以找到兩個表中創建鏈接字段值相等的記錄 --查詢學員信息顯示班級名稱 select Student.StudentNo,Student.StudentName,grade.classname from Student inner join grade on Student.ClassId=grade.ClassId
--左鏈接: 關鍵字前面的表是左表,後面的表是右表 --左鏈接能夠獲得左表全部數據,若是創建關聯的字段值在右表中不存在,那麼右表的數據就以null值替換 select PhoneNum.*,PhoneType.* from PhoneNum left join PhoneType on PhoneNum.pTypeId=PhoneType.ptId
--右鏈接: 關鍵字前面的表是左表,後面的表是右表 --右鏈接能夠獲得右表全部數據,若是創建關聯的字段值在右左表中不存在,那麼左表的數據就以null值替換 select PhoneNum.*,PhoneType.* from PhoneNum right join PhoneType on PhoneNum.pTypeId=PhoneType.ptId
--full join :能夠獲得左右鏈接的綜合結果--去重複 select PhoneNum.*,PhoneType.* from PhoneNum full join PhoneType on PhoneNum.pTypeId=PhoneType.ptId

17.事務
一種處理機制。以事務處理的操做,要麼都能成功執行,要麼都不執行。

事務的四個特色 ACID:

  • A:原子性:事務必須是原子工做單元;對於其數據修改,要麼全都執行,要麼全都不執行。它是一個總體,不能再拆分
  • C:一致性:事務在完成時,必須使全部的數據都保持一致狀態。。某種程度的一致
  • I:隔離性:事務中隔離,每個事務是單獨的請求將單獨的處理,與其它事務沒有關係,互不影響
  • D:持久性:若是事務一旦提交,就對數據的修改永久保留

使用事務:

將你須要操做的sql命令包含在事務中。

1.在事務的開啓和事務的提交之間
2.在事務的開啓和事務的回滾之間

三個關鍵語句:

  • 開啓事務:begin transaction
  • 提交事務:commit transaction
  • 回滾事務:rollback transaction
declare @num int =0 --記錄操做過程當中可能出現的錯誤號 begin transaction update bank set cmoney=cmoney-500 where name='aa' set @num=@num+@@ERROR --說明這一句的執行有錯誤 可是不能在語句執行的過程當中進行提交或者回滾 --語句塊是一個總體,若是其中一句進行了提交或者回滾,那麼後面的語句就再也不屬於當前事務, --事務不能控制後面的語句的執行 update bank set cmoney=cmoney+500 where name='bb' set @num=@num+@@ERROR select * from bank if(@num<>0 ) --這個@@ERROR只能獲得最近一一條sql語句的錯誤號 begin print '操做過程當中有錯誤,操做將回滾' rollback transaction end else begin print '操做成功' commit transaction end --事務一旦開啓,就必須提交或者回滾 --事務若是有提交或者回滾,必須保證它已經開啓

18.視圖

視圖就是一張虛擬表,能夠像使用子查詢作爲結果集同樣使用視圖。

select * from vw_getinfo

使用代碼建立視圖。

語法:

create view vw_自定義名稱 as 查詢命令 go
--查詢全部學員信息 if exists(select * from sysobjects where name='vw_getAllStuInfo') drop view vw_getAllStuInfo go --上一個批處理結果的標記 create view vw_getAllStuInfo as --能夠經過聚合函數獲取因此記錄數 select top (select COUNT(*) from Student) Student.StudentNo,Student.StudentName,grade.ClassId,grade.classname from Student inner join grade on Student.ClassId=grade.ClassId order by StudentName --視圖中不能使用order by --select * from grade --只能建立一個查詢語句 --delete from grade where ClassId>100 --在視圖中不能包含增長刪除修改 go --使用視圖。。就像使用表同樣 select * from vw_getAllStuInfo --對視圖進行增長刪除和修改操做--能夠對視圖進行增長刪除和修改操做,只是建議不要這麼作:所發能夠看到:若是操做針對單個表就能夠成功,可是若是 多張的數據就會報錯:不可更新,由於修改會影響多個基表。 update vw_getAllStuInfo set classname='asdas' ,studentname='aa' where studentno=1

19.觸發器

觸發器:執行一個能夠改變表數據的操做(增長刪除和修改),會自動觸發另一系列(相似於存儲過程當中的模塊)的操做。

語法:

create trigger tr_表名_操做名稱 on 表名 after|instead of 操做名稱 as go
if exists(select * from sysobjects where name='tr_grade_insert') drop trigger tr_grade_insert go create trigger tr_grade_insert on grade for insert ---爲grade表建立名稱爲tr_grade_insert的觸發器,在執行insert操做以後觸發 as declare @cnt int set @cnt = (select count(*) from student) select * ,@cnt from student select * from grade go --觸發器不是被調用的,而是被某一個操做觸 發的,意味着執行某一個操做就會自動觸發 觸發器 insert into grade values('fasdfdssa') ---替換觸 發器:原本須要執行某一個操做,結果不作了,使用觸 發器中的代碼語句塊進行替代 if exists(select * from sysobjects where name='tr_grade_insert') drop trigger tr_grade_insert go create trigger tr_grade_insert on grade instead of insert ---爲grade表建立名稱爲tr_grade_insert的觸發器,在執行insert操做以後觸發 as declare @cnt int set @cnt = (select count(*) from student) select * ,@cnt from student select * from grade go insert into grade values('aaaaaaaaaaaa') go ---觸 發器的兩個臨時表: --inserted: 操做以後的新表:全部新表與原始的物理表沒有關係,只與當前操做的數據有關 --deleted:操做以前的舊錶:全部新表與原始的物理表沒有關係,只與當前操做的數據有關 if exists(select * from sysobjects where name='tr_grade_insert') drop trigger tr_grade_insert go create trigger tr_grade_insert on grade after insert as print '操做以前的表:操做以前,這一條記錄尚未插入,因此沒有數據' select * from deleted print '操做以後的表:已經成功插入一條記錄,全部新表中有一條記錄' select * from inserted go --測試: insert into grade values('aaaaa') if exists(select * from sysobjects where name='tr_grade_update') drop trigger tr_grade_update go create trigger tr_grade_update on grade after update as print '操做以前的表:存儲與這個修改操做相關的沒有被修改以前的記錄' select * from deleted print '操做以後的表:存儲這個操做相關的被修改以後 記錄' select * from inserted go --測試 update grade set classname=classname+'aa' where ClassId>15 if exists(select * from sysobjects where name='tr_grade_delete') drop trigger tr_grade_delete go create trigger tr_grade_delete on grade after delete as print '操做以前的表:存儲與這個修改操做相關的沒有被刪除以前的記錄' select * from deleted print '操做以後的表:存儲這個操做相關的被刪除以後 記錄--沒有記錄' select * from inserted go --測試 delete from grade where ClassId>15

20.存儲過程

存儲過程就至關於c#中的方法
參數,返回值,參數默認值,參數:值的方式調用
在調用的時候有三個對應:類型對應,數量對應,順序對應。

建立語法:

create proc usp_用戶自定義名稱 對應方法的形參 --(int age, out string name) as 對應方法體:建立變量,邏輯語句,增長刪除修改和查詢..return返回值 go

調用語法:

exec 存儲過程名稱 實參,實參,實參 ...
--獲取全部學員信息 if exists(select * from sysobjects where name='usp_getAllStuInfo') drop proc usp_getAllStuInfo go create procedure usp_getAllStuInfo as select * from Student go --調用存儲過程,獲取的有學員信息 execute usp_getAllStuInfo --exec sp_executesql 'select * from Student' --查詢指定性別的學員信息 go if exists(select * from sysobjects where name='usp_getAllStuInfoBySex') drop proc usp_getAllStuInfoBySex go create procedure usp_getAllStuInfoBySex @sex nchar(1) --性別 參數不須要declare as select * from Student where Sex=@sex go --調用存儲過程,獲取指定性別的學員信息 Exec usp_getAllStuInfoBySex '女' --建立存儲過程獲取指定班級和性別的學員信息 go if exists(select * from sysobjects where name='usp_getAllStuInfoBySexandClassName') drop proc usp_getAllStuInfoBySexandClassName go create procedure usp_getAllStuInfoBySexandClassName @classname nvarchar(50), --班級名稱 @sex nchar(1)='男'--性別 有默認的參數建議寫在參數列表的最後 as declare @classid int ---班級ID set @classid=(select classid from grade where classname=@classname) --經過參數班級名稱獲取對應的班級ID select * from Student where Sex=@sex and ClassId=@classid go --執行存儲過程獲取指定班級和性別的學員信息 --exec usp_getAllStuInfoBySexandClassName '八期班' exec usp_getAllStuInfoBySexandClassName default, '八期班' --有默認值的參數能夠傳遞default exec usp_getAllStuInfoBySexandClassName @classname='八期班' --也能夠經過參數=值的方式調用 exec usp_getAllStuInfoBySexandClassName @classname='八期班' ,@sex='女' exec usp_getAllStuInfoBySexandClassName @classname='八期班',@sex='女' --建立存儲過程,獲取指定性別的學員人數及總人數 go if exists(select * from sysobjects where name='usp_getCountBySexandClassName') drop proc usp_getCountBySexandClassName go create procedure usp_getCountBySexandClassName @cnt int=100 output, --output標記說明它是一個輸出參數。output意味着你向服務器請求這個參數的值,那麼在執行的時候,服務器發現這個參數標記了output,就會將這個參數的值返回輸出 @totalnum int =200output, --總人數 @className nvarchar(50), --輸入參數沒有默認值,在調用的時候必須傳入值 @sex nchar(1)='男'--輸入參數有默認值,用戶能夠選擇是否傳入值 as declare @classid int ---班級ID set @classid=(select classid from grade where classname=@classname) --經過參數班級名稱獲取對應的班級ID select * from Student where Sex=@sex and ClassId=@classid set @cnt= (select COUNT(*) from Student where Sex=@sex and ClassId=@classid) --獲取指定班級和性別的總人數 set @totalnum=(select COUNT(*) from Student) ----獲取總人數 go --調用存儲過程,獲取指定性別的學員人數及總人數 declare @num int,@tnum int exec usp_getCountBySexandClassName @cnt=@num output ,@totalnum=@tnum output , @className='八期班' print @num print @tnum print '作完了' ---獲取指定班級的人數 if exists(select * from sysobjects where name='usp_getCount') drop proc usp_getCount go create procedure usp_getCount @className nvarchar(50)='八期班' as declare @classid int=(select classid from grade where classname=@className) declare @cnt int set @cnt =(select COUNT(*) from Student where ClassId=@classid) --return 只能返回int整數值 --return '總人數是'+cast(@cnt as varchar(2)) return @cnt go --調用存儲過程,接收存儲過程的返回值 declare @count int --set @count=(exec usp_getCount) exec @count=usp_getCount '八期班' print @countif exists(select*from sysobjects where name='usp_getClassList') drop proc usp_getClassList go create procedure usp_getClassList asselect classid,classname from grade go

21.分頁存儲過程

if exists(select * from sysobjects where name='usp_getPageData') drop proc usp_getPageData go create procedure usp_getPageData @totalPage int output,--總頁數 @pageIndex int =1 ,--當前頁碼,默認是第一頁 @pageCount int =5 --每一頁顯示的記錄數 as select * from (select ROW_NUMBER() over(order by studentno) id,* from Student) temp where temp.id>(@pageindex-1)*@pagecount and temp.id<=(@pageindex*@pagecount) set @totalPage=CEILING((select COUNT(*) from Student)*1.0/@pageCount) go

22.索引

select * from sysindexes --create index IX_Student_studentName --on 表名(字段名) --clustered index:彙集索引 nonclustered index--非彙集索引 if exists(select * from sysindexes where name='IX_Student_studentName') drop index student.IX_Student_studentName go create clustered index IX_Student_studentName on student(studentname) --若是是先建立主鍵再建立彙集索引就不能夠,由於主鍵默認就是彙集索引 --可是若是先建立彙集索引,那麼還能夠再建立主鍵,由於主鍵不必定須要是彙集的

23.臨時表

--建立局部臨時表 create table #newGrade ( classid int , classname nvarchar(50) ) ---局部臨時表只有在當前建立它的會話中使用,離開這個會話臨時表就失效.若是關閉建立它的會話,那麼臨時表就會消失 insert into #newGrade select * from grade  select * from #newGrade select * into #newnewnew from grade select * into newGrade from #newgrade --建立全局臨時表:只要不關閉當前會話,全局臨時表均可以使用,可是關閉當前會話,全局臨時表也會消失 create table ##newGrade ( classid int , classname nvarchar(50) ) drop table ##newGrade select * into ##newGrade from grade select * from ##newGrade --建立表變量 declare @tb table(cid int,cname nvarchar(50)) insert into @tb select * from grade select * from @tb

文章源自:http://www.cnblogs.com/gameworld/p/4790881.html

相關文章
相關標籤/搜索