1. 程式人生 > 其它 >SQLSqlserver珍藏多年的小筆記

SQLSqlserver珍藏多年的小筆記

--使用者建立自定義資料型別,MR_NXT 是庫
use MR_NXT 
exec sp_addtype postcode ,'char(8)','not null'

--SQL Server2008 提供多種強制資料完整性的機制
--(1)空值和非空值(NULL 或者 NOT NULL)
    --允許空值(NULL) 預設情況下,列循序為空值,即允許使用者在新增資料時省略該列的值
    --不允許空值(NOT NULL)不允許在沒有指定列預設值的情況下忽略該列的值
--(2)預設值(default)
    --如果在插入行是沒有指定列的值,那麼預設值將指定列中所使用的值,預設值可以是去任何取值為常量的物件
--在Create Table中使用Default關鍵字建立預設定義,將常量表達式值派為列的預設值,這是標準方法 --在Create Defalut語句建立預設物件,然後使用sp_bindefalut系統儲存過程將它繫結到列上,這是一種向前相容的功能 --(3)特定標識屬性(Identity)標識列自增長 --資料庫中如果某列被指派定標識屬性(Identity),系統將自動為表插入的新行生成連續遞增的編號, --因為標識值通常唯一,所以標識列常定義為主鍵(PK,primary key) --一個列不能同時具有NULL屬性和IDentity屬性,二者只能選其一
--(4)約束(constraints) --SQL是用來定義SQLServer2008自動強制資料庫完整性的方式,使用約束優先於使用觸發器、規則和預設值,下面有5中約束 --非空(NOT NULL)使使用者必須在表的指定列中輸入一個值,每個表中可以有多個非空約束 --檢查(CHECK)用來指定一個布林操作,限制輸入到表中的值 --唯一性(Unique)使使用者的應用程式必須向列中輸入一個唯一的值,值不能重複,但可以為空 --主鍵(PK,Primary key)建立一列或多列的組合以唯一標識表中的每一行,主鍵可以保證實體完整性,一個表只能有一個主鍵,同時主鍵中的列不能接受空值
--外來鍵(FK,foreign key)用於建立和加強兩個表資料之間的連結的一列或多列,當一個表中作為主鍵的一列被新增到另一個表中時,連結就建立了,主要目的是控制儲存在外來鍵表中的資料 --備份型別 --完整備份:完整備份包括特定資料庫(或者一組特定的檔案組或檔案)中的所有資料,以及可以恢復這些資料的足夠的日誌 --差異備份:差異備份基於資料的最新備份,這稱為差異的基準或者差異基準,差異基準是讀/寫資料的完整備份,差異備份僅包括自建立差異基準後發生更改的資料, --通常,建立基準備份之後很短時間內執行的差異備份的基準更小,建立速度也更快,因此,使用差異備份可以加快進行頻繁備份的速度,從而降低資料丟失的風險 --檔案備份:可以分別備份和還原資料庫中的檔案,使用檔案備份能夠只還原損壞的檔案.而不用還原資料庫的其餘部分,從而加快了恢復恢復 --恢復模式 --簡單恢復:允許將資料庫恢復到最新的備份,簡單恢復更容易管理,但如果資料檔案損壞,出現數據丟失的風險係數會很高 --完整恢復:允許將資料庫恢復到故障點狀態,完整恢復提供了最大的靈活性,使資料庫可以恢復到早期時間點,在最大範圍內防止出現故障時丟失資料, --於簡單恢復型別相比,完整恢復模式和大容量日誌恢復模式向資料提供更多的保護 --大容量日誌恢復:允許大容量日誌記錄操作,大容量日誌恢復模式是對完全恢復模式的補充,對某些大規模操作(如建立索引或大容量複製),它比完全恢復模式效能 --更高,佔用的日誌空間會更少,不過,大容量日誌恢復模式會降低時點恢復的靈活性。 --T-SQL語言的組成 --資料定義語言(Data Definition Language,DDL):用於在資料庫系統中對資料庫、表、檢視、索引等資料庫物件進行建立和管理 --資料控制語言(Data Control Language,DCL):用於在資料庫系統中資料的完整性、安全性等的控制 --資料操縱語言(Data Mainpulation Language,DML):用於插入、修改、刪除和查詢資料庫中的資料 --T-SQL語言結構語法如下: --SELECT 子句 [into 子句] from [子句] [where 子句] [group by 子句] [having 子句] [order by 子句] --查詢表中女的資訊 --select * from student where Sex='女' order by StuAge --資料常量的各個位之間不要加逗號,例如,123123這個數字不能表示為: 123,123,浮點常量使用符號e來指定,例如:1.5e3,-3.14e1, e被讀作"乘10的幾次冪" --日期和時間常量,SQL規定日期、時間和時間間隔的常量值被指定為日期和事件的常量,例如: '2018-11-14', yyyy-MM-dd(時間格式), --Current_Date、SYSDate和getDate()三個獲取當前時間的區別: Current_date 返回的是當前會話時間,而sysDate返回的是伺服器時間,Date返回的是當前客戶端的時間 --區域性變數,區域性變數名必須以@開頭 --(1)宣告區域性變數需要使用Declare --Declare{ @varable_name datatyp [...]} --引數說明 @varable_name的變數必須以@開頭,另外變數名的形式必須符合SQLserver識別符號的命名方法 --dataType:區域性變數使用的資料型別,可以是除了Text、ntext或者image型別以外的系統資料型別 --宣告區域性變數 @songname的SQL語句以下: --declate @songaname char(10) --(2)為區域性變數賦值,一種是select語句,另一種是set語句,使用select語句為變數賦值的語法如下 --SEELCT @varable_name=expression from table_name where clause --註釋符 可以使用ANSI標準的註釋符(--),用於單行註釋,多行註釋(/*開頭*/結尾) --運算子是一種符號,用來進行常量、變數或者列之間的數字列算和比較操作,T-SQL語言運算子有:演算法運算子、賦值運算子、比較運算子、邏輯運算子、位運算子、連線運算子 --演算法運算子在兩個表示式上執行數字運算,這兩個表示式可以是數字資料型別分類:(+、-、*、/) declare @x int ,@y int ,@z int select @x=2,@y=5 set @z=@x%@y print @z --賦值運算子即賦值運算子,即等號(=),使用賦值運算子將引數設定成一個由表示式返回的值 --第一種解決方式 declare @songname char(20) set @songname='loving' print @songname --第二種解決方式 declare @song_name char(20) select @song_name='loveIng' print @song_name --比較運算子測試兩個表示式是否相同,除了text/ntextt或image資料型別的表示式外,比較運算子可以用於所有的表示式,表示式() use OA4T111 select * from userInfo where sex='' and PassWOrd=1 --位運算子的運算元可以是整數資料型別或二進位制串資料型別(image資料型別除外) -- % 按位and -- | 按位or -- ^ 按位互斥or -- ~ 按位not --連線運算子“+”用於連線兩個或兩個以上的字元或二進位制串、列名或串和列的混合體,將一個串加入到另一個串的末尾 declare @name char(20) set @name=' 最愛' print '我喜歡的電影是'+@name --萬用字元是指匹配指定範圍內或者屬於方括號所指定的集合中的任意單個字元,可以在涉及模式匹配的字串比較( Like,Patindex) -- like %a% 是指包含a的模糊查詢 select patindex('%abb%','abcaabbeeabb') --patindex select patindex(%abb%,'abcaavveeabb') 結果是5,也就是abb第一次出現的位置 --流程控制語句 --begin end 語句用於將多個Transact-SQL語句組合為一個邏輯塊,當流程控制語句必須執行一個包含兩條或兩條以上的T-SQL語句 begin select * from Role end --在begin ...end語句中完成把兩個變數的值交換 declare @tempx int , @tempy int ,@t int set @tempx=1 set @tempy=2 begin set @t=@tempx set @tempx=@tempy set @tempy=@t end print @tempx print @tempy -- if else IF<表示式> {命令列|程式塊} else {命令列1|程式塊1} --判斷數字3是否是正數 declare @ift int set @ift=3 if @ift>0 print '@ift是正數' print 'end' --判斷數字8的奇偶行 declare @ifnum int set @ifnum=8 if @ifnum%2=0 print '@ifnum是奇數' print 'end' --判斷兩個數8和3的大小 declare @ifnum8 int,@ifnum3 int set @ifnum8=8 set @ifnum3=3 if @ifnum8>@ifnum3 print '@ifnum8大於@ifnum3' else print '@ifnum3小於@ifnum8' --輸入一個座標值,然後判斷它在哪一個象限 declare @ifnuma int,@ifnumb int set @ifnuma=8 set @ifnumb=-3 if @ifnuma>0 if @ifnumb>0 print '位於第一象限' else print '位於第四象限' else if @ifnumb>0 print '位於第二象限' else print '位於第三象限' --case好處可以避免編寫多重if than巢狀迴圈 use mr_nxt go select *, 備註=case when grade>=90 then '成績優秀' when grade>=80 then '成績良好' when grade>=70 then '成績及格' else '不合格' end from [dbo].[tb_Grade] --while 在條件為真的情況下,while子句可以迴圈地執行其後的一條T-SQL語句 --求1-10之間的整數的和 declare @n int ,@sum int set @n=1 set @sum=0 while @n<=10 begin set @sum+=@n --也可以使用 set @sum= @sum+@n set @n+=1 end print @sum --continue 命令可以讓程式跳過continue命令之後的語句 --break --求1-10之間的偶數的和,並用continue控制語句輸出 declare @x1 int, @sumoushu int set @x1=1 set @sumoushu=0 while @x1<10 begin set @x1+=1 if @x1%2=0 set @sumoushu+=@x1 else continue end print @sumoushu --return 語句用於查詢或過程無條件退出,return語句可在任何時候用於從過程、批處理或語句塊退出,位於return之後的語句不會被執行, --語法 return [整數值] declare @xreturn int set @xreturn=3 if @xreturn>0 print '遇到return之前' return print '遇到return之後' --goto 命令用來改變程式執行的流程,使流程跳到識別符號指定的程式再繼續往下執行 --語法 goro 識別符號需要在其後面加上一個冒號 ":" declare @xgoto int select @xgoto=1 loving: print @xgoto select @xgoto+=1 while @xgoto<=3 goto loving --waitfor 觸發器 waitfor delay '00:00:03' print '生日快樂小可愛111' waitfor time '23:22:10' print '生日快樂小可愛222' --T-SQL語句操作資料庫之 --資料庫的建立 create Database Mrkj on primary ( name=Mrkj_data, FileName='E:\SQLData\DataBase\Mrkj.mdf', Size=5mb, maxsize=unlimited, filegrowth=10% ) log on ( Name=Mrkj_log, FileName='E:\SQLData\DataBase\Mrkj.ldf', Size=3mb, maxsize=50mb, filegrowth=2mb ) create Database Ming on primary ( name=Ming_data, FileName='E:\SQLData\DataBase\Ming.mdf', Size=5mb, maxsize=unlimited, filegrowth=10% ) log on ( Name=Ming_log, FileName='E:\SQLData\DataBase\Ming.ldf', Size=3mb, maxsize=50mb, filegrowth=2mb ) --使用Alert database修改檔案或者檔案組 --將一個大小為10MB的資料刻檔案mrkj新增到MRKJ資料庫中,該資料檔案的大小為為10MB,最大的檔案大小為100MB,增長速度為2MB,更改mdf路徑 --修改檔案大小時,修改後的大小要大於修改前的大小, database 資料庫 use Mrkj alter database MrKJ add file ( name=mrkj, FileName='E:\SQLData\DataBasecs\Mrkj.mdf', Size=10mb, maxsize=100MB, filegrowth=10% ) --使用儲存過程修改資料庫名稱 將資料庫名稱更改 use Ming exec sp_renamedb 'Ming', 'MR' --刪除資料庫 use master drop database MR --使用CreateTable語句建立表 use MR_NXT create table Student( Id int not null, Name varchar(50), Age int ) --建立、修改和刪除約束 --1.非空約束決定表中的性是否可為該列包含空值,空值(或Null)不同於零(0)、空白或者長度為0的字串(如""),Null的意思是沒有輸入,出現Null通常表示未知或未定義 --(1)建立非空約束 alter table Student add constraint checkIsNull check ( Name is not null) --(2)修改非空約束 alter table student alter column Id int null --主鍵約束 --(1)建立主鍵約束 use MR_NXT create table Product ( Id int constraint pk_Id primary key, ProductName varchar(50), Size varchar(50), State int constraint checkState check (State is not null) ) --(2)在現有表中建立主鍵的約束 use MR_NXT alter table student add constraint _Id primary key(Id) --(3)刪除主鍵約束 use MR_NXT alter table student drop constraint Id --唯一約束unique用於強制實施集中值的唯一性,根據unIque約束,表中的任何兩行都不能出現相同的列值 --(1)建立Emoloyee,並將欄位Id設定唯一約束 use MR_NXT create table Employee ( Id int constraint UQ_ID unique, Name char(50), Sex char(2), Age int ) --(2)在現有表中建立唯一約束 use MR_NXT alter table Employee add constraint unique_Id unique(Id) --刪除唯一約束 use MR_NXT alter table Employee drop constraint unique_Id --檢查約束Check可以強制域的完整性,Check約束類似foreign key,可以控制進入列中的值 --(1)建立檢查約束 use MR_NXT --drop table Employee create table Employee ( Id int constraint UQ_ID unique, Name char(50), Sex char(2) constraint Ck_Sex check(sex in ('','')), Age int ) --(2)在現有表中建立檢查格式如下 use MR_NXT alter table employee add constraint Check_Sex Check(sex='') --(3)刪除檢查約束 use MR_NXT alter table employee drop constraint Check_Sex --預設約束 --(1)建立表時建立預設約束,將Sex設定預設約束為女 use MR_NXT --drop table Employee create table Employee ( Id int constraint UQ_ID unique, Name char(50), Sex char(2) constraint def_sex default '', Age int ) --(2)在現有表中建立預設約束 use MR_NXT alter table Employee add constraint def_sex default '' for Sex --(3)刪除預設約束 use MR_NXT alter table employee drop constraint def_sex --外來鍵約束 --(1)建立表時建立外來鍵約束 use MR_NXT create table Loborage ( Id int, Wage Money constraint fkey_Id foreign key(Id) references Employee(Id) ) --(2)在現有表中建立外來鍵約束 use MR_NXT alter table Loborage add constraint Fkey_Id foreign key(Id) references Employee(Id) --(3)刪除外來鍵約束 use MR_NXT alter table Loborage drop constraint Fkey_Id --使用alter table 修改表結構 --(1)向資料庫Student表中新增Name欄位 use MR_NXT alter table student add Name char(2) --(2)將Student表中Name的欄位的資料型別修改為char(50) use MR_NXT alter table student alter column Name char(50) --(3)刪除Student表中Name欄位 use MR_NXT alter table student drop column Name --使用Drop table 語句刪除表 drop database 表名 --資料操作 --使用SELECT 語句瀏覽資料表 select * from Employee --使用Insert語句新增資料 insert into Employee values('001','小明','','19') --使用updaate語句修改指定資料 update Employee set Age+=1aa update Employee set Age='18' where Name='張三' --指定Name條件 --使用delete語句刪除指定資料 delete Employee where Id='001' --檢視操作 --建立Emoloyee表中的所有記錄的檢視View_Emp create view View_Emp as select * from Employee --建立繫結到架構的檢視view1 create view View1 with schemabinding as select name,sex from Employee with check option --with子句 臨時命名的結果集,計算沒一年齡的數量 use MR_NXT with ageReps(age,agecount)as ( select age,COUNT(*) from Employee as AgeReports where Age is not Null group by Age ) select age,agecount from ageReps --查詢最大的Age use MR_NXT select distinct 員工編號=Id, Name as 姓名, Sex 性別,Age 年齡 from Employee select *from Employee --into 建立新表並將來自查詢結果行插入新表中 select Name,Age into tb_Employee from Employee select *from tb_Employee --where 子句 select *from Employee where Name='雨欣' And Age=25 --邏輯運算子(Not And OR) select *from Employee where Sex='' And not Age=22 or Sex='' and Age=25 --Like % 關鍵字模糊查詢 select *from Employee where Name like '%欣%' And Age=25 --Like 帶特殊字元需要轉義的 select *from Employee where Name like '%\%%' escape '\'; -- Like _(下劃線)匹配任意單個字元 select *from Employee where Name like '_欣' And Age=25 --lIKE []萬用字元,表示查詢一定範圍內的單個字元[2~4]表示2到4的數,包括2,3,4, 2[2~4]就表示22,23,24,條件加上單引號'' select *from Employee where Age like '2[2-5]' --使用Between 關鍵字 欄位 between 條件 And 條件 || 欄位 Not between 條件 And 條件指定範圍條件 select *from Employee where Age between 22 and 27 --不在範圍內的Not Between and select *from Employee where Age not between 22 and 27 --使用In關鍵字 select *from Employee where Id in(13,14) --使用 Not In關鍵字 select *from Employee where Id not in(14) --All、SOME、 ANY關鍵字 --All 這是查詢大於張三 Age的資料 select *from Employee where Age >ALL ( select age from Employee where name in('張三') ) --ANY 大於最大值 select *from Employee where Age >ANY ( select age from Employee where name in('張三') ) --Exists關鍵字用於指定一個子查詢,測試行是否存在 select * from Employee where exists (select null) --Group By子句 按一個或多個列或表示式的值將一組選定行組合成一個集,針對每一組返回一行 --按性別分組,使用聚合函式列需要包含在子句中select Sex select Sex from Employee group by Sex --將年齡和性別分組 select Sex,age from Employee group by Sex,age --Having 子句 查詢每個年齡段的人數大於等於兩人的年齡 select Age 年齡, count(*) 人數 from Employee group by Age having COUNT(Age)>=2 --Group by 子句 返回的列中所使用的排序順序,除非同時指定了TOP,否則orderby子句在子查詢、檢視、行內函數中無效 --ASC 指定按升序,從最低值到最高值對指定列中的值進行排序(從小到大) --desc 指定按降序,從最高值到最低值對指定列中的值進行排序(從大到小) select * from Employee where sex='' order by Age desc select * from Employee where Age>=18 order by Name asc --compute子句 select * from Employee order by Sex compute avg(Age) select * from Employee order by Sex compute avg(Age) by sex --Distinct 去重複的記錄Age select distinct Age from Employee --TOP關鍵字 限制顯示的行數 select top 5 Name,Age from Employee --union合併多個查詢結果,預設地,UNION 操作符選取不同的值。如果允許重複的值,請使用 UNION ALL。 SELECT Name FROM Student UNION SELECT Name FROM Student SELECT * FROM Student --union all 合併表 --新增點資料 insert into Student(Age,Sex,Name)values(18,'','張三') insert into Student(Age,Sex,Name)values(19,'','王五') insert into Student(Age,Sex,Name)values(20,'','趙六') insert into Student(Age,Sex,Name)values(28,'','孫⑦') insert into Student(Age,Sex,Name)values(25,'','李⑦') --union all 合併表,UNION 結果集中的列名總是等於 UNION 中第一個 SELECT 語句中的列名。資料將會重複 SELECT Name,Age FROM Student UNION ALL SELECT Name,Age FROM Student --使用union合併有不同列數的兩個表,如果列數不夠則使用Null來新增 select Id,Sex ,age from Student union all select cno,CNAME,NULL from course --使用union進行多表的資料合併 select Id,Sex from Student union select cno,CNAME from course union select Id,Name from Employee --子查詢是一個可以巢狀在select、insert、update、delete語句或其他子查詢中的查詢,任何允許使用表示式的地方都可以使用子查詢 --查詢tb_Grade 中Name是王五的 select * from Student where Name=(select Name FROM tb_Grade WHERE Name='王五') --帶in的巢狀查詢 Name是王五的 select * from Student where Name in (select Name FROM tb_Grade ) --帶 not in的巢狀查詢 Name是王五的 select * from Student where Name not in (select Name FROM tb_Grade ) --沒有參加過考試的學生 select * from Student where Name not in (select Name FROM tb_Grade where Name is not null ) --帶exitst的巢狀查詢 select * from Student where Exists (select Name FROM tb_Grade where Student.Id=tb_Grade.ID ) --聯接查詢 --內部連線 Inner join select * from Student stu inner join tb_Grade tb on stu.Id=tb.ID --左外部連線 Left join,如果左邊的有一行沒有匹配到右邊的一行,那麼右邊變成空值Null select * from Student stu left join tb_Grade tb on stu.Id=tb.ID --右外部連線 Right join,如果右邊的有一行沒有匹配到左邊的一行,那麼左邊變成空值Null select * from Student stu right join tb_Grade tb on stu.Id=tb.ID --完整外連線 full join ,,如果有一行沒有匹配到,那麼其他沒有匹配到的變成空值Null select * from Student stu full join tb_Grade tb on stu.Id=tb.ID --交叉聯接,如果student 有6行資料,Course有5行,那麼表中最後的行數是(5*6)30行 select * from Student stu cross join tb_Grade --case語句更新資料,如果是男的年齡-1,如果是女的年齡+1 update Student set Age=case when Sex='' then Age-1 when Sex='' then Age+1 end --Create Proc 語句建立儲存過程 Create Procedure Proc_Student @Proc_Sno int as select * from Student where Id=@Proc_Sno --使用Execute 執行儲存過程 Create Procedure proStudentValues as select top 3 * from Student --Exec執行儲存過程 exec proStudentValues --檢視儲存過程 --使用sp_helptext檢視儲存過程的定義 select * from sys.sql_modules exec sp_helptext 'proStudentValues' --修改儲存過程 alter procedure proStudentValues @sno varchar(10) as select * from student --觸發器的概念 SQLServer提供兩種主要機制來強制使用業務規則和資料完整性,即約束和觸發器 --觸發器是一種特殊型別的儲存過程,當指定表中的資料傳送變化時觸發器自動生效 --觸發器的優點, --(1)觸發器自動執行,對錶中的資料進行修改後,觸發器立即被啟用 --(2)為了實現複雜的資料庫更新操作,觸發器可以呼叫一個或多個儲存過程,甚至可以通過呼叫外部過程 --(3)觸發器能夠實現比CHECK約束更為複雜的資料完整性約束,在資料庫中,為了實現資料完整性,可以使用Check約束和觸發器 --Check約束不允許引用其他表中的列來完成檢查檢查工作,而觸發器可以引用其他表中的列,觸發器更適合在大型資料庫管理系統中用來約束資料的完整性 --(4)觸發器可以檢測資料庫內的操作,從而取消了資料庫未經許可的操作,使用資料庫修改、更新操作更加安全,資料庫的執行也很穩定 --(5)一個表可以同時存在3個不同操作的觸發器(Insert、update、delete) --觸發器的常規種類DML觸發器、DDL觸發器和登入觸發器 --建立DML觸發器,當資料庫發生資料操作語言時將會呼叫DML觸發器 Create Trigger Trigger_Product on product after insert as raiserror('正在想表中插入資料',16,10) insert into Product values('觸發器1111','50g',0) --建立DDL觸發器,這些事件知主要對應Create、Alter、drop,類似DDL操作的某些系統儲存過程 Create trigger Trigger_ProductDDL on database for drop_Table, alter_Table as print '只有,"Trigger_ProductDDL"觸發器無效時,才可以刪除或修改表' rollback --rollback 如果資料被刪除後修改操作進行回滾,顯示提示 --只有對修改、刪除product表時觸發器才顯示資訊 drop table Product --建立登入觸發器 use master go create login yy with password='TMsoft' must_change, check_ExPiration=on; go grant view server state to yy; go Create trigger connection_limit_trigger ON ALL Server with Execute as 'yy' for login as begin if ORIGINAL_LOGIN()='yy' And (select COUNT(*) from sys.dm_exec_sessions where is_user_process=1 and original_login_name='yy')>1 rollback end; --檢視觸發器 --(1)通過sp-helptext檢視觸發器 exec sp_helptext 'Trigger_Product' --(2)通過sys.Objects顯示,查詢型別為TR的觸發器 select * from sys.objects where type='TR' --修改觸發器 可以通過alter trigger 語句實現 --插入、修改、刪除資料時先提示資訊 alter trigger Trigger_Product on product after insert,update,delete as raiserror ('正在向表中插入、修改或者刪除資料',16,10) --修改DML觸發器,防止使用者修改資料 alter trigger Trigger_ProductDDL on database for drop_Table, alter_Table as print '只有,"Trigger_ProductDDL"觸發器無效時,才可以刪除或修改表' rollback --重新命名觸發器 exec sp_rename '原觸發器名稱','新觸發器名稱' exec sp_rename 'trigger_Product','trigger_Product_DML' --禁用和啟用觸發器 --使用disable trigger 語句禁用DML觸發器 disable trigger trigger_Product on product --使用disable trigger 語句啟用DML觸發器 enable trigger trigger_Product on product --刪除觸發器 drop trigger trigger_Product --刪除DDL觸發器 drop trigger trigger_Product on database --刪除登入觸發器 drop trigger trigger_Product on all server --索引的優點 /* (1)建立唯一索引,保證資料庫表中每一行資料的唯一性 (2)大大加速資料的檢索速度,這也是建立索引的最主要的原因 (3)加速表和表至今的連線,特別是在實現資料的參考完整性特別有意義 (4)使用分組和排序子句進行資料檢索時,同樣可以減少查詢中分組和排序的時間 (5)通過使用索引,可以在查詢的過程中使用優化隱藏器,提供系統的效能 */ --索引的缺點 /* (1)建立索引和維護索引需要耗費時間,這種時間隨著資料量增加而增加 (2)索引需要佔物理空間,除了資料表佔資料空間之外,每一個索引還要佔一定的物理空間,如果要建立聚集引用,那麼需要的空間就會更大 (3)當對錶中的資料進行新增修改刪除時,索引也要動態地維護,降低了資料的維護速度 */ --索引的分類有聚集索引、非聚集索引、唯一索引、包含性索引、索引檢視、全文索引、空間索引、篩選索引和XML索引 --聚集索引除了可以提高查詢效能外,還可以按需重新生成或重新組織來控制表碎片 --非聚集索引具有獨立於資料行的結構,非聚集索引包含非聚集索引鍵值,並且每個鍵值項都有指向包含該鍵值的資料行的指標 --建立非聚集索引 use MR_NXT create index ix_student_no on Student(id) --建立唯一聚集索引,無法對錶建立多個聚集索引 use MR_NXT create unique clustered index ix_Product_no on Product(id) --SQL遊標,允許定位在結果集的特定行,從結果集的當前位置檢索一行或一部分行,支援對結果集中的資料庫資料所做的更改提供不同級別的可見性支援 --遊標的實現 /* (1)宣告遊標 (2)開啟遊標 (3)從一個遊標中查詢資訊 (4)關閉遊標 (5)釋放遊標 */ --遊標的型別(靜態遊標、動態遊標、只進遊標、鍵集驅動遊標) /* (1)靜態遊標的完整結果集在遊標開啟時建立在tempdb中,靜態遊標總是按照遊標開啟時的原樣顯示結果集 (2)動態遊標與靜態遊標相對,當滾動遊標時,動態遊標反映結果集中所作的所有更改,結果集中的行資料值、順序和成員在每次提取時都會改變 (3)只進遊標不支援滾動,它只支援遊標從頭到尾順序提取,只在從資料庫中提取查出來才能進行檢索 (4)開啟遊標時,鍵集驅動遊標中的成員和行順序是固定,鍵集驅動遊標由一套被稱為鍵集的唯一識別符號控制 */ --建立遊標 use MR_NXT declare Cur_Emp cursor for select * from Employee go --建立一個名為Cu_Emp_01的只讀遊標 use MR_NXT declare Cur_Emp_01 cursor for select * from Employee for read only --只讀遊標,不允許遊標內資料被更新 go --建立Cur_Emp_02的更新遊標 use MR_NXT declare Cur_Emp_02 cursor for select Name,Sex,Age from Employee for update --只讀遊標,不允許遊標內資料被更新 go --開啟遊標可以使用Open命令 declare Emp_01 cursor for --宣告遊標 select * from Employee where Id=13 open Emp_01 --開啟遊標 go --使用@@fetch_status控制一個where迴圈的遊標 declare ReadCursor cursor for select * from student open ReadCursor fetch next from readCursor while @@FETCH_STATUS=0 begin fetch next from ReadCursor end --關閉遊標 Global 是全域性遊標 declare CloseCursor cursor for select * from Student for read only open CloseCursor close CloseCursor --釋放遊標,當遊標關閉之後,並沒有在記憶體中釋放所佔用的系統資源,所有可以使用Deallocate命令刪除遊標引用 --釋放需要釋放的遊標CloseCursor declare FreeCurosor cursor for select * from Student open freecursor close freecursor deallocate freecursor --使用系統過程檢視遊標 sp_cursor_list 和sp_descride_cursor檢視遊標的屬性 --宣告一個遊標,並使用sp_cursor_list declare Cur_Employee cursor for select Name from Employee where Name like '張%' open Cur_Employee declare @Report cursor exec sp_cursor_list @cursor_return=@Report output, @cursor_scope=2 fetch next from @Report while (@@FETCH_STATUS<>-1) begin fetch next from @Report end close @Report deallocate @Report go close Cur_Employee deallocate Cur_Employee go --宣告一個遊標,並使用exec sp_describe_cursor declare Cur_Employee cursor for select Name from Employee open Cur_Employee declare @Report cursor exec sp_describe_cursor @cursor_return=@Report output, @cursor_source=N'global',@cursor_identity=N'Cur_Employee' fetch next from @Report while (@@FETCH_STATUS<>-1) begin fetch next from @Report end close @Report deallocate @Report go close Cur_Employee deallocate Cur_Employee go --SQL函式的使用 /*聚合函式概述 SUM 返回表示式中所有值的和 AVG 計算平均值 Min 返回表示式的最小值 Max 返回表示式的最大值 Ccount 返回組專案的數量 distinct 返回一個集合,並從指定集合中刪除重複的元組 */ select * from tb_grade --修改表型別 alter table tb_grade alter column Grade int --SUM(求和)函式 select SUM(Age) as 總年齡 from Student --AVG(平均)函式 select Avg(Age) as 平均年齡 from Student --MIN(最小)函式 select MIN(Age) as 最小年齡 from Student --MAX(最大)函式 select MAX(Age) as 最大年齡 from Student --count(返回int數量)函式 select COUNT(*) as 總資料 from Student --distinct(去重)函式 select distinct Name as 去重姓名 from Student --查詢不重複記錄函式 select distinct (Name) from Student order by Name --查詢重複記錄函式 select Name,COUNT(Name) from Student group by Name having count(Name)>1 order by Name --ABS(絕對值)函式 select ABS(1.0) as '1.0的絕對值', ABS(0.0) as '0.0的絕對值', ABS(-1.0) as '-1.0的絕對值' --圓(圓周率)函式 select PI() AS 圓周率 --Power(乘方)函式 select Power(2,2) as '2的冪', Power(3,3) as '3的冪', Power(4,4) as '4的冪' --Rand(隨機浮點數)函式 select RAND(100),RAND(),RAND() --字串函式 --CharIndex返回字串的起始位置,下標從1開始 select CHARINDEX('',Name) from Student where Id=3 select * from Student --Left(取左邊指定的字元) select LEFT('無敵小可愛',2) select LEFT(Name,1) ,count(LEFT(Name,1))from Student group by LEFT(Name,1) --Right(取左邊指定的字元) 假設Id 00001 取後面3位Right(Id,3) select Right('無敵小可愛',2) select Right(Id,1) ,count(Right(Id,1))from Student group by Right(Id,1) --Len返回字元個數函式 select len('ABCDE') AS 個數 --replace替換字串 select REPLACE('MingMing','ing','i') AS 替換結果 --reverse反轉函式 select reverse('MingMing') AS 反轉結果 --STR函式返回由數字資料轉換來的字元資料 select STR(123.45) as 'STT' select STR(123.45,5,1) as 'STT' select STR(123.45,8,1) as 'STT' --Substring select SUBSTRING('abcde',1,2) --日期和時間函式 /*常用時間函式及說明 DateAdd 在向指定日期加上一段時間的基礎上,返回新的datetime值 DataFill 返回跨2個指定日期的日期和時間邊界數 getdate 返回當前系統日期和時間 day 返回日期中的天的整數 month 返回日期中的月份的整數 year 返回日期中的年份的整數 */ --GetDate(返回當前系統日期和時間) select GETDATE() as 當前時間 --Day(返回當前指定日期的天) select DAY('2018-12-2') as 'Day' --Month(返回當前指定日期的天) select Month('2018-12-2') as 'Month' --Year(返回當前指定日期的天),資料庫將0解釋為1900年1月1日 select Year('2018-12-2') as 'Year' --DateDiff(返回日期和時間的邊界數),計算開始時間和結束時間距離了多久 select DATEDIFF(DAY,'2018-4-12','2018-12-2') as 時間差距 --DateAdd(新增時間)在當前時間添加了一個月時間,可以用於電商下單,控制下單時間派送 select DATEADD("Month",1,getdate()) as 加一個月的時間 select DATEADD(YEAR,1,getdate()) as 加一個月的時間 --轉換函式 --Cast函式 select CAST('Mingrikeji' as nvarchar(6)) as 結果 --轉nvarchar型別 select GETDATE() as unConvertDateTim, cast(Getdate() as nvarchar(30)) as UsingCast, Convert(nvarchar(30),Getdate(),126) as UsingConvertTo_Is GO --轉時間型別 select GETDATE() as unConvertDateTim, cast(Getdate() as datetime) as UsingCast, Convert(datetime,Getdate(),126) as UsingConvertTo_Is GO --返回資料庫名稱 select DB_NAME() as [Current DataBase]; go --SQL事務 /*事務的概念,事務包含4中重要的屬性,被稱為ACID(原子性、一致性、隔離性和永續性),一個事務必須通過ACID (1)原子性:事務是一個整體的工作單元,事務對資料庫所作的操作要麼全部執行,要麼全部不執行 (2)一致性:事務在完成時,必須使所有的資料都保持一致狀態,在相關資料庫中,所有規則二都必須應用事務的修改,以保持 所有資料的完整性,如果事務成功,則所有的資料將變成一個新的狀態,如果事務失敗,則所有輸幾局將處於開始之前的狀態 (3)隔離性:由某一事務所作的修改必須與其他啊事務所作的修改隔離,事務檢視資料時資料所處的狀態,要麼是另一併發事務 修改它之前的狀態,要麼是另一事務修改它之後的狀態,事務不會檢視中間狀態的資料 (4)永續性:當事務提交後,對資料庫所作的修改就會永久儲存下來 */ --開始事務 select * from Employee where Id=13 begin transaction Update_data update Employee set Name='章子婷' where Id=13 commit transaction Update_data select * from Employee where Id=13 --結束事務,當一個事務執行完成之後,要將其結束,以便釋放所佔用的記憶體資源,結束事務使用Commit語句 select * from Employee begin transaction Insert_data insert into Employee values('16','門聞雙','','22') commit transaction Insert_data go if @@ERROR=0 print '插入新紀錄成功' go select * from Employee --事務的工作機制 select * from Employee begin transaction Update_Dat update Employee set Name='聞雙' where Id=16 Delete Employee where Id=16 commit transaction Update_Dat --事務的隔離性 --Read Uncommitted(未提交讀) begin transaction update Employee set Name='章子婷' set transaction isolation level read uncommitted --設定未提交隔離級別 commit transaction select * from Employee --Read Committed(提交讀) set transaction isolation level read uncommitted begin transaction select * from Employee rollback transaction set transaction isolation level read uncommitted --設定提交隔離級別 update Employee set Name='章子婷' --Repeatable Read(提交讀) set transaction isolation level Repeatable Read begin transaction select * from Employee rollback transaction set transaction isolation level Repeatable Read --設定提交隔離級別 insert into Employee values('16','星星','','25') --Serializable set transaction isolation level Serializable begin transaction select * from Employee rollback transaction set transaction isolation level Serializable --設定可序列讀 delete from Employee wHere Id=13 --SQL檢視鎖 select * from sys.dm_tran_locks --建立分散式事務 set Xact_Abort on begin distributed transaction update Employee set Name='星星' where Id=16 update Employee set Name='婷子' where Id=16 commit transaction Update_Dat
生命中最值得欣慰的,莫過於一覺醒來,你還在身旁