乡下人产国偷v产偷v自拍,国产午夜片在线观看,婷婷成人亚洲综合国产麻豆,久久综合给合久久狠狠狠9

  • <output id="e9wm2"></output>
    <s id="e9wm2"><nobr id="e9wm2"><ins id="e9wm2"></ins></nobr></s>

    • 分享

      新手熱點(diǎn)必看-SQL勁爆語句全集

       東西二王 2019-05-26

      SQL語句全集

      新手熱點(diǎn)必看-SQL勁爆語句全集

      SQL語句全集

      1.什么是SQL語句

      sql語言:結(jié)構(gòu)化的查詢語言。(Structured Query Language),是關(guān)系數(shù)據(jù)庫管理系統(tǒng)的標(biāo)準(zhǔn)語言。

      它是一種解釋語言:寫一句執(zhí)行一句,不需要整體編譯執(zhí)行。

      語法特點(diǎn):

      1.沒有“ ”,字符串使用‘ ’包含

      2.沒有邏輯相等,賦值和邏輯相等都是=

      3.類型不再是最嚴(yán)格的。任何數(shù)據(jù)都可以包含在‘ ’以內(nèi)

      4.沒有bool值的概念,但是在視圖中可以輸入true/false

      5.它也有關(guān)系運(yùn)算符:> < >= <= = <> != ,它返回一個(gè)bool值

      6.它也有邏輯運(yùn)算符: !(not) &&(and) ||(or)

      7.它不區(qū)別大小寫

      2.使用sql語句創(chuàng)建數(shù)據(jù)庫和表

      語法:

      create database 數(shù)據(jù)庫名稱

      on primary –默認(rèn)在主文件組上

      (

      name=’邏輯名稱_data’ , –當(dāng)你發(fā)現(xiàn)它不是一句完整的sql語句,而僅僅是一個(gè)處理結(jié)構(gòu)中的某一句的時(shí)候,就需要添加 ,

      size=初始大小,–數(shù)值不包含在‘’以內(nèi)

      filegrowth=文件增長 ,

      maxsize=最大容量,

      filename=’物理路徑’

      )

      log on

      (

      name=’邏輯名稱_log’ , –當(dāng)你發(fā)現(xiàn)它不是一句完整的sql語句,而僅僅是一個(gè)處理結(jié)構(gòu)中的某一句的時(shí)候,就需要添加 ,

      size=初始大小,–數(shù)值不包含在‘’以內(nèi)

      filegrowth=文件增長 ,

      maxsize=最大容量, –一般來說日志文件不限制最大容量

      filename=’物理路徑’

      )

      --判斷數(shù)據(jù)庫文件是否已經(jīng)存在 :數(shù)據(jù)庫的記錄都存儲(chǔ)在master庫中的sysdatabases表中

      --自動(dòng)切換當(dāng)前數(shù)據(jù)庫

      --使用代碼開啟外圍應(yīng)該配置器

      exec sp_configure 'show advanced options' ,1

      RECONFIGURE

      exec sp_configure 'xp_cmdshell',1

      RECONFIGURE

      --自定義目錄 xp_cmdshell可以創(chuàng)建出目錄 'mkdir f:\project':指定創(chuàng)建目錄

      exec xp_cmdshell 'mkdir f:\project'

      use master

      --exists 函數(shù)判斷()中的查詢語句是否返回結(jié)果集,如果返回了結(jié)果集則得到true,否則得到false

      if exists( select * from sysdatabases where name='School')

      drop database School --刪除當(dāng)前指定名稱的數(shù)據(jù)庫

      create database School

      on primary

      (

      name='School_data',--邏輯名稱.說明最多能夠存儲(chǔ)100mb數(shù)據(jù),如果沒有限制就可以將硬盤存儲(chǔ)滿

      size=3mb,--初始大小

      maxsize=100mb,--最大容量

      filegrowth=10%,--文件增長一次增長10%

      filename='f:\project\School_data.mdf'

      ),

      --創(chuàng)建文件組

      filegroup mygroup

      (

      name='School_data1',--邏輯名稱.說明最多能夠存儲(chǔ)100mb數(shù)據(jù),如果沒有限制就可以將硬盤存儲(chǔ)滿

      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.創(chuàng)建數(shù)據(jù)表

      語法:

      create table 表名

      (

      字段名稱 字段類型 字段特征(是否為null,默認(rèn)值 標(biāo)識(shí)列 主鍵 唯一鍵 外鍵 check約束),

      字段名稱 字段類型 字段特征(是否為null,默認(rèn)值 標(biāo)識(shí)列 主鍵 唯一鍵 外鍵 check約束)

      )

      創(chuàng)建老師表Teacher :Id、Name、Gender、Age、Salary、Birthday

      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),--可以同時(shí)創(chuàng)建多個(gè)特征,用空格 分隔開。 identity是標(biāo)識(shí)列,第一個(gè)參數(shù)是種子,第二個(gè)是增量

      Name nvarchar(50) not null,-- not null標(biāo)記它的值不能為null--不能不填寫

      ClassId int not null,

      Gender bit not null,

      Age int ,

      Salary money, --如果不標(biāo)記為 not null.那么就相當(dāng)于標(biāo)記了null

      Birthday datetime

      )

      4.數(shù)據(jù)完整性約束

      實(shí)體完整性:實(shí)體就是指一條記錄。這種完整性就是為了保證每一條記錄不是重復(fù)記錄。是有意義的

      – 主鍵:非空和唯一.一個(gè)表只有一個(gè)主鍵,但是一個(gè)主鍵可以是由多個(gè)字段組成的 組合鍵

      – 標(biāo)識(shí)列:系統(tǒng)自動(dòng)生成,永遠(yuǎn)不重復(fù)

      – 唯一鍵:唯一,但是可以為null,只能null一次

      域完整性:域就是指字段,它是為了保證字段的值是準(zhǔn)和有效,合理值

      – 類型 是否null,默認(rèn)值,check約束,關(guān)系

      自定義完整性:

      – check約束 , 存儲(chǔ)過程 觸發(fā)器

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

      – 1.建立引用的字段類型必須一致

      – 2.建立引用的字段的意義一樣

      – 3.建立主外鍵關(guān)系的時(shí)候選擇 外鍵表 去建立主外鍵關(guān)系

      – 4.建立主外鍵關(guān)系的字段在主表中必須是主鍵或者唯一鍵

      – 5.對(duì)于操作的影響 :

      – 1.在添加數(shù)據(jù)時(shí),先添加主鍵表再添加外鍵表數(shù)據(jù)

      – 2.在刪除的時(shí)候先外鍵表數(shù)據(jù)再刪除主鍵表數(shù)據(jù)

      – 級(jí)聯(lián)的操作:不建議使用:會(huì)破壞數(shù)據(jù)完整性

      – 不執(zhí)行任何操作:該報(bào)錯(cuò)就報(bào)錯(cuò),該刪除就刪除

      – 級(jí)聯(lián):刪除主表記錄,從表引用該值的記錄也被刪除

      – 設(shè)置null:刪除主表記錄,從表對(duì)應(yīng)的字段值設(shè)置為null,前提是可以為null

      – 設(shè)置為default:刪除主表記錄,從表對(duì)應(yīng)的字段值設(shè)置為default,前提是可以為default

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

      語法:

      alter table 表名

      add constraint 前綴_約束名稱 約束類型 約束說明(字段 關(guān)系表達(dá)式 值)

      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)

      --同時(shí)創(chuàng)建salary的默認(rèn)約束和age的check約束

      alter table teacher

      add constraint DF_Teacher_Salary default(5000) for salary,

      constraint CK_Teacher_Age check(age>0 and age<=100)

      --為teacher表的classid字段創(chuàng)建主外鍵

      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 --不檢查現(xiàn)有數(shù)據(jù)

      add constraint FK_Teacher_Classes_Classid foreign key(classid) references classes(classid)

      --on delete set default 級(jí)聯(lián)操作

      --不執(zhí)行任何操作:該報(bào)錯(cuò)就報(bào)錯(cuò),該刪除就刪除 --no action --默認(rèn)選擇

      --級(jí)聯(lián):刪除主表記錄,從表引用該值的記錄也被刪除 --cascade

      --設(shè)置null:刪除主表記錄,從表對(duì)應(yīng)的字段值設(shè)置為null,前提是可以為null --set null

      --設(shè)置為default:刪除主表記錄,從表對(duì)應(yīng)的字段值設(shè)置為default,前提是可以為default --set default

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

      --len(參數(shù)) --獲取指定參數(shù)內(nèi)容的字符個(gè)數(shù)

      select LEN('abcd') 【4】運(yùn)行結(jié)果

      select LEN('中華人民共和國') 【7】

      --DataLength(參數(shù)):獲取指定內(nèi)占據(jù)的字節(jié)數(shù)--空間大小

      select DataLength('abcd') 【4】

      select DataLength('中華人民共和國') 【14】

      --char類型:當(dāng)空間分配后,不會(huì)因?yàn)榇鎯?chǔ)的內(nèi)容比分配的空間小就回收分配的空間。但是如果存儲(chǔ)的內(nèi)容超出了指定的空間大小,就會(huì)報(bào)錯(cuò),當(dāng)你存儲(chǔ)的內(nèi)容的長度變化區(qū)間不大的時(shí)候可以考慮使用char

      select LEN(char) from CharTest 【2】

      select DataLength(char) from CharTest 【10】

      --varchar var--變化的:當(dāng)你存儲(chǔ)的內(nèi)容小于分配的空間的時(shí)候,多余的空間會(huì)自動(dòng)收縮。但是如果存儲(chǔ)的內(nèi)容超出了指定的空間大小,就會(huì)報(bào)錯(cuò) 當(dāng)存儲(chǔ)的內(nèi)容波動(dòng)區(qū)間比較大時(shí)候使用varchar

      select LEN(varchar) from CharTest 【2】

      select DataLength(varchar) from CharTest 【2】

      --nchar-- n代表它是一個(gè)unicode字符。規(guī)定不管什么樣的字符都占據(jù)兩個(gè)字節(jié)。 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基本語句

      數(shù)據(jù)插入

      調(diào)用方法 一 一對(duì)應(yīng)原則:類型對(duì)應(yīng),數(shù)量對(duì)應(yīng),順序?qū)?yīng)

      語法: 形參 實(shí)參

      insert into 表名([字段列表]) values(值列表) –數(shù)據(jù)必須要符合數(shù)據(jù)完整性

      插入操作是單個(gè)表的操作

      插入操作insert一次只能插入一條記錄

      use School

      --插入teacher所有字段的數(shù)據(jù).如果在表后沒有指定需要插入的字段名稱,那么就默認(rèn)為所有字段添加值

      --但是一定需要注意的是:標(biāo)識(shí)列永遠(yuǎn)不能自定義值--不能人為插入值

      --僅當(dāng)使用了列列表并且 IDENTITY_INSERT 為 ON 時(shí),才能為表'Teacher'中的標(biāo)識(shí)列指定顯式值。

      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的字段可以不賦值

      --列名或所提供值的數(shù)目與表定義不匹配

      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)

      --為有默認(rèn)值的字段插入值:

      --1.不寫這一列讓系統(tǒng)自動(dòng)賦值

      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)

      --數(shù)據(jù)必須完全符合表的完整性約束

      insert into Teacher(Name,ClassId,Gender,Age,Salary,Birthday) values('趙六1',5,1,300,default,null)

      --任意類型的數(shù)據(jù)都可以包含在''以內(nèi), 不包括關(guān)鍵字

      insert into Teacher(Name,ClassId,Gender,Age,Salary,Birthday) values('馬鵬飛','5','0','15',default,null)

      --但是字符串值如果沒有包含在''以內(nèi).會(huì)報(bào)錯(cuò) 列名 '蘭鵬' 無效。

      insert into Teacher(Name,ClassId,Gender,Age,Salary,Birthday) values('蘭鵬','5','0','15',default,null)

      --但是數(shù)值組成的字符串可以不使用''包含

      insert into Teacher(Name,ClassId,Gender,Age,Salary,Birthday) values(123,'5','0','15',default,null)

      --日期值必須包含在’‘以內(nèi),否則就是默認(rèn)值

      insert into Teacher(Name,ClassId,Gender,Age,Salary,Birthday) values('鄒元標(biāo)2','5','0','15',default,'1991-9-11')

      數(shù)據(jù)刪除

      語法:

      delete [from] 表名 where 條件

      delete from Teacher where Age<20

      --特點(diǎn):

      --1.刪除是一條一條進(jìn)行刪除的

      --2.每一條記錄的刪除都需要將操作寫入到日志文件中

      --3.標(biāo)識(shí)列不會(huì)從種子值重新計(jì)算,以從上次最后一條標(biāo)識(shí)列值往下計(jì)算

      --4.這種刪除可以觸發(fā)delete觸發(fā)器

      --truncate table 表名 --沒有條件,它是一次性刪除所有數(shù)據(jù)

      --特點(diǎn):

      --1.一次性刪除所有數(shù)據(jù),沒有條件,那么日志文件只以最小化的數(shù)據(jù)寫入

      --2.它可以使用標(biāo)識(shí)列從種子值重新計(jì)算

      --3.它不能觸發(fā)delete觸發(fā)器

      truncate table teacher

      數(shù)據(jù)更新(數(shù)據(jù)修改):一定需要考慮是否有條件

      語法:

      update 表名 set 字段=值,字段=值 。。where 條件

      update Teacher set Gender='true'

      --修改時(shí)添加條件

      update Teacher set Gender=0 where Id=20

      --多字段修改

      update Teacher set ClassId=4,Age =5,Salary=5000 where Id=22

      --修改班級(jí)id=4,同時(shí)年齡》20歲的人員工資 500

      update Teacher set Salary=Salary 500 where ClassId=4 and Age>20

      數(shù)據(jù)檢索–查詢

      語法: *代表所有字段

      select */字段名稱列表 from 表列表

      select StudentNo,StudentName,Sex,[Address] from Student

      --可以為標(biāo)題設(shè)置 別名,別名可以是中文別名

      select StudentNo as 學(xué)號(hào),StudentName 姓名,性別=Sex,[Address] from Student

      --添加常量列

      select StudentNo as 學(xué)號(hào),StudentName 姓名,性別=Sex,[Address] ,國籍='中華人民共和國' from Student

      select的作用

      --select的作用

      --1.查詢

      --2.輸出

      select 1 1

      -- 是運(yùn)算符,系統(tǒng)會(huì)自動(dòng)為你做類型轉(zhuǎn)換

      select 1 '1'

      select '1' 1

      --如果 兩邊都是字符串,那么它就是一字符串連接符

      select '1' '1'

      select 'a' 1

      --可以輸出多列值

      select 1,2,34,3,545,67,567,6,7

      --Top、Distinct

      select * from Student

      --top可以獲取指定的記錄數(shù),值可以大于總記錄數(shù).但是不能是負(fù)值

      select top 100 * from Student

      --百分比是取ceiling()

      select top 10 percent * from Student

      --重復(fù)記錄與原始的數(shù)據(jù)表數(shù)據(jù)無關(guān),只與你查詢的結(jié)果集有關(guān)系 distinct可以去除結(jié)果集中的重復(fù)記錄--結(jié)果集中每一列的值都一樣

      select distinct LoginPwd,Sex,Email from Student

      select distinct Sex from Student

      聚合函數(shù)

      --聚合函數(shù):

      --1.對(duì)null過濾

      --2.都需要有一個(gè)參數(shù)

      --3.都是返回一個(gè)數(shù)值

      --sum():求和:只能對(duì)數(shù)值而言,對(duì)字符串和日期無效

      --avg():求平均值

      --count():計(jì)數(shù):得到滿足條件的記錄數(shù)

      --max():求最大值:可以對(duì)任意類型的數(shù)據(jù)進(jìn)行聚合,如果是字符串就比較拼音字母進(jìn)行排序

      --min():求最小值

      --獲取學(xué)員總?cè)藬?shù)

      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

      --注意細(xì)節(jié):

      select SUM(StudentName) from Student

      select SUM(BornDate) from Student

      select min(StudentName) from Student

      select max(StudentName) from Student

      --查詢學(xué)號(hào),姓名,性別,年齡,電話,地址 ---查詢女生

      select StudentNo,StudentName,Sex,BornDate,Address from Student where Sex='女' and BornDate >'1990-1-1' and Address='廣州傳智播客'

      --指定區(qū)間范圍

      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'

      --查詢班級(jí)id 1 3 5 7的學(xué)員信息

      select * from Student where ClassId=1 or ClassId=3 or ClassId=5 or ClassId=7

      --指定具體的取值范圍--可以是任意類型的范圍.值的類型需要一致--可以相互轉(zhuǎn)換

      select * from Student where ClassId in(1,3,'5',7)

      select * from Student where ClassId not in(1,3,'5',7)

      模糊查詢

      --帶條件的查詢-模糊查詢-- 只針對(duì)字符串而言

      --查詢 姓 林 的女生信息

      --=是一種精確查詢,需要完全匹配

      select * from Student where Sex='女' and StudentName='林'

      --通配符--元字符

      --%:任意個(gè)任意字段 window:* 正則表達(dá)式 :.*

      --_:任意的單個(gè)字符

      --[]:代表一個(gè)指定的范圍,范圍可以是連續(xù)也可以是間斷的。與正則表達(dá)式完全一樣[0-9a-zA-Z].可以從這個(gè)范圍中取一個(gè)字符

      --[^]:取反值

      select * from Student where Sex='女' and StudentName='林%'

      --通配符必須在模糊查詢關(guān)鍵的中才可以做為通配符使用,否則就是普通字符

      --like 像 。。。。一樣

      select * from Student where Sex='女' and StudentName like '林%'

      select * from Student where Sex='女' and StudentName like '林_'

      --[]的使用 學(xué)號(hào)在11~15之間的學(xué)員信息

      select * from Student where StudentNo like '[13579]'

      ---處理null值

      --null:不是地址沒有分配,而是不知道你需要存儲(chǔ)什么值 所以null是指 不知道。但是=只能匹配具體的值,而null根本就不是一個(gè)值

      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

      分組統(tǒng)計(jì)

      --當(dāng)你看到 每一個(gè),,各自,不同,,分別 需要考慮分組

      --查詢每一個(gè)班級(jí)的男生人數(shù)

      --與聚合函數(shù)一起出現(xiàn)在查詢中的列,要么也被聚合,要么被分組

      select classid,Sex,COUNT(*) from Student where Sex='男' group by ClassId,sex

      --查詢每一個(gè)班級(jí)的總?cè)藬?shù),顯示人數(shù)>=2的信息

      --1.聚合不應(yīng)出現(xiàn)在 WHERE 子句中--語法錯(cuò)誤

      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 數(shù)據(jù)源做篩選 group by 分組字段列表 having 分組結(jié)果集做篩選 Order by 對(duì)結(jié)果集做記錄重排

      select ClassId ,COUNT(*) as num from Student where Email is not null GROUP by ClassId order by ClassId desc

      --關(guān)于top的執(zhí)行順序 排序之后再取top值

      select top 1 ClassId ,COUNT(*) as num from Student GROUP by ClassId order by num desc

      7.類型轉(zhuǎn)換函數(shù)

      --select :輸出為結(jié)果集--虛擬表

      --print:以文本形式輸出 只能輸出一個(gè)字符串值.

      print 1 'a'

      select 1,2

      select * from Student

      --類型轉(zhuǎn)換

      --Convert(目標(biāo)類型,源數(shù)據(jù),[格式]) --日期有格式

      print '我的成績是:' convert(char(3),100)

      print '今天是個(gè)大日子:' convert(varchar(30),getdate(),120)

      select getdate()

      select len(getdate())

      --cast(源數(shù)據(jù) as 目標(biāo)類型) 它沒有格式

      print '我的成績是:' cast(100 as char(3))

      8.日期函數(shù)

      --getdate():獲取當(dāng)前服務(wù)器日期

      select GETDATE()

      --可以在源日期值是追加指定時(shí)間間隔的日期數(shù)

      select DATEADD(dd,-90,GETDATE())

      --dateDiff:找到兩個(gè)日期之間指定格式的差異值

      select StudentName,DATEDIFF(yyyy,getdate(),BornDate) as age from Student order by age

      --DATENAME:可以獲取日期的指定格式的字符串表現(xiàn)形式

      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.數(shù)學(xué)函數(shù)

      --rand:隨機(jī)數(shù):返回0到1之間的數(shù),理論上說可以返回0但是不能返回1

      select RAND()

      --abs:absolute:取絕對(duì)值

      select ABS(-100)

      --ceiling:獲取比當(dāng)前數(shù)大的最小整數(shù)

      select CEILING(1.00)

      --floor:獲取比當(dāng)前數(shù)小的最大整數(shù)

      select floor(1.99999)

      power:

      select POWER(3,4)

      --round():四舍五入.只關(guān)注指定位數(shù)后一位

      select ROUND(1.549,1)

      --sign:正數(shù)==1 負(fù)數(shù) ==-1 0=0

      select SIGN(-100)

      select ceiling(17*1.0/5)

      10.字符串函數(shù)

      --1.CHARINDEX --IndexOf():能夠返回一個(gè)字符串在源字符串的起始位置。找不到就返回0,如果可以找到就返回從1開始的索引--沒有數(shù)組的概念

      --第一個(gè)參數(shù)是指需要查詢的字符串,第二個(gè)是源字符串,第三個(gè)參數(shù)是指從源字符的那個(gè)索引位置開始查找

      select CHARINDEX('人民','中華人民共和國人民',4)

      --LEN():可以返回指定字符串的字符個(gè)數(shù)

      select LEN('中華人民共和國')

      --UPPER():小寫字母轉(zhuǎn)換為大寫字母 LOWER():大寫轉(zhuǎn)小寫

      select LOWER(UPPER('sadfasdfa'))

      --LTRIM:去除左空格 RTIRM:去除右空格

      select lTRIM(RTRIM(' sdfsd ')) 'a'

      --RIGHT:可以從字符串右邊開始截取指定位數(shù)的字符串 如果數(shù)值走出范圍,不會(huì)報(bào)錯(cuò),只會(huì)返回所有字符串值,但是不能是負(fù)值

      select RIGHT('中華人民共和國',40)

      select LEFT('中華人民共和國',2)

      --SUBSTRING()

      select SUBSTRING('中華人民共和國',3,2)

      --REPLACE 第一個(gè)參數(shù)是源字符串,第二個(gè)參數(shù)是需要替換的字符串,第三個(gè)參數(shù)是需要替換為什么

      select REPLACE('中華人民共和國','人民','居民')

      select REPLACE('中 華 人民 共 和 國',' ','')

      --STUFF:將源字符串中從第幾個(gè)開始,一共幾個(gè)字符串替換為指定的字符串

      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.聯(lián)合結(jié)果集union

      --聯(lián)合結(jié)果集union

      select * from Student where Sex='男'

      --union

      select * from Student where Sex='女'

      --聯(lián)合的前提是:

      --1.列的數(shù)量需要一致:使用 UNION、INTERSECT 或 EXCEPT 運(yùn)算符合并的所有查詢必須在其目標(biāo)列表中有相同數(shù)目的表達(dá)式

      --2.列的類型需要可以相互轉(zhuǎn)換

      select StudentName,Sex from Student --在字符串排序的時(shí)候,空格是最小的,排列在最前面

      union

      select cast(ClassId as CHAR(3)),classname from grade

      --union和union all的區(qū)別

      --union是去除重復(fù)記錄的

      --union all不去除重復(fù) :效率更高,因?yàn)椴恍枰袛嘤涗浭欠裰貜?fù),也沒有必須在結(jié)果庥是執(zhí)行去除重復(fù)記錄的操作。但是可以需要消耗更多的內(nèi)存存儲(chǔ)空間

      select * from Student where ClassId=2

      union all

      select * from Student where ClassId=2

      --查詢office這科目的全體學(xué)員的成績,同時(shí)在最后顯示它的平均分,最高分,最低分

      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

      --一次性插入多條數(shù)據(jù)

      --1.先將數(shù)據(jù)復(fù)制到另外一個(gè)新表中,刪除源數(shù)據(jù)表,再將新表的數(shù)據(jù)插入到源數(shù)據(jù)表中

      --1.select */字段 into 新表 from 源表

      --1.新表是系統(tǒng)自動(dòng)生成的,不能人為創(chuàng)建,如果新表名稱已經(jīng)存在就報(bào)錯(cuò)

      --2.新表的表結(jié)構(gòu)與查詢語句所獲取的列一致,但是列的屬性消失,只保留非空和標(biāo)識(shí)列。其它全部消失,如主鍵,唯一鍵,關(guān)系,約束,默認(rèn)值

      select * into newGrade from grade

      truncate table grade

      select * from newGrade

      --select * into grade from newGrade

      --2.insert into 目標(biāo)表 select 字段列表/* from 數(shù)據(jù)源表

      --1、目標(biāo)表必須先存在,如果沒有就報(bào)錯(cuò)

      --2.查詢的數(shù)據(jù)必須符合目標(biāo)表的數(shù)據(jù)完整性

      --3.查詢的數(shù)據(jù)列的數(shù)量和類型必須的目標(biāo)的列的數(shù)量和對(duì)象完全對(duì)應(yīng)

      insert into grade select classname from newGrade

      delete from admin

      --使用union一次性插入多條記錄

      --insert into 表(字段列表)

      --select 值。。。。 用戶自定義數(shù)據(jù)

      --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函數(shù)用法

      相當(dāng)于switch case—c#中的switch…case只能做等值判斷

      這可以對(duì)字段值或者表達(dá)式進(jìn)行判斷,返回一個(gè)用戶自定義的值,它會(huì)生成一個(gè)新列

      2.要求then后面數(shù)據(jù)的類型一致

      1.第一種做等值判斷的case..end

      case 字段或者表達(dá)式

      when .值..then .自定義值

      when .值..then .自定義值

      …..

      else 如果不滿足上面所有的when就滿足這個(gè)else

      end

      --顯示具體班級(jí)的名稱

      select StudentNo,StudentName,

      case ClassId --如果case后面接有表達(dá)式或者字段,那么這種結(jié)構(gòu)就只能做等值判斷,真的相當(dāng)于switch..case

      when 1 then '一班'

      when 2 then '2班'

      when 3 then '3班'

      when null then 'aa' --不能判斷null值

      else '搞不清白'

      end,

      sex

      from Student

      --2.做范圍判斷,相當(dāng)于if..else,它可以做null值判斷

      --case --如果沒有表達(dá)式或者字段就可實(shí)現(xiàn)范圍判斷

      -- when 表達(dá)式 then 值 --不要求表達(dá)式對(duì)同一字段進(jìn)行判斷

      -- when 表達(dá)式 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

      --百分制轉(zhuǎn)換為素質(zhì)教育 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值,只能使用關(guān)系運(yùn)算符表達(dá)式

      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 '成績不錯(cuò),輸出前三名:'

      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循環(huán)語法

      沒有{},使用begin..end

      沒有bool值,需要使用條件表達(dá)式

      可以嵌套

      也可以使用break,continue

      go

      declare @subjectName nvarchar(50)='office' --科目名稱

      declare @subjectId int--科目ID

      declare @classid int =(select classid from Subject where SubjectName=@subjectName) --查詢當(dāng)前科目屬于那一個(gè)班級(jí)

      set @subjectId=(select SubjectId from Subject where SubjectName=@subjectName) --獲取科目ID

      declare @totalCount int --總?cè)藬?shù) :那一個(gè)班級(jí)需要考試這一科目

      set @totalCount=(select COUNT(*) from Student where ClassId=@classid)

      print @totalcount --14

      declare @unpassNum int --不及格人數(shù)

      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

      --執(zhí)行循環(huán)加分

      update Result set StudentResult =2 where SubjectId=@subjectId and StudentNo in(select StudentNo from Student where ClassId=@classid) and StudentResult<=98

      --重新計(jì)算不及格人數(shù)

      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) --查詢當(dāng)前科目屬于那一個(gè)班級(jí)

      set @subjectId=(select SubjectId from Subject where SubjectName=@subjectName) --獲取科目ID

      declare @totalCount int --總?cè)藬?shù)

      set @totalCount=(select COUNT(*) from Student where ClassId=@classid)

      print @totalcount --14

      declare @unpassNum int --不及格人數(shù)

      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.子查詢

      子查詢–一個(gè)查詢中包含另外一個(gè)查詢。被包含的查詢就稱為子查詢,。包含它的查詢就稱父查詢

      1.子查詢的使用方式:使用()包含子查詢

      2.子查詢分類:

      1.獨(dú)立子查詢:子查詢可以直接獨(dú)立運(yùn)行

      查詢比“王八”年齡大的學(xué)員信息

      select * from Student where BornDate<(select BornDate from Student where StudentName=’王八’)

      2.相關(guān)子查詢:子查詢使用了父查詢中的結(jié)果

      --子查詢的三種使用方式

      --1.子查詢做為條件,子查詢接在關(guān)系運(yùn)算符后面 > < >= <= = <> !=,如果是接這關(guān)系運(yùn)算符后面,必須保證 子查詢只返回一個(gè)值

      --查詢六期班的學(xué)員信息

      select * from Student where ClassId=(select ClassId from grade where classname='八期班')

      --子查詢返回的值不止一個(gè)。當(dāng)子查詢跟隨在 =、!=、<、<=、>、>= 之后,或子查詢用作表達(dá)式時(shí),這種情況是不允許的。

      select * from Student where ClassId=(select ClassId from grade)

      --查詢八期班以外的學(xué)員信息

      --當(dāng)子查詢返回多個(gè)值(多行一列),可以使用in來指定這個(gè)范圍

      select * from Student where ClassId in(select ClassId from grade where classname<>'八期班')

      --當(dāng)沒有用 EXISTS 引入子查詢時(shí),在選擇列表中只能指定一個(gè)表達(dá)式。如果是多行多列或者一行多列就需要使用exists

      --使用 EXISTS 關(guān)鍵字引入子查詢后,子查詢的作用就相當(dāng)于進(jìn)行存在測試。外部查詢的 WHERE 子句測試子查詢返回的行是否存在

      select * from Student where EXISTS(select * from grade)

      select * from Student where ClassId in(select * from grade)

      --2.子查詢做為結(jié)果集--

      select top 5 * from Student --前五條

      --使用top分頁

      select top 5 * from Student where StudentNo not in(select top 5 studentno from Student)

      --使用函數(shù)分頁 ROW_NUMBER() over(order by studentno),可以生成行號(hào),排序的原因是因?yàn)椴煌呐判蚍绞将@取的記錄順序不一樣

      select ROW_NUMBER() over(order by studentno),* from Student

      --查詢擁有新生成行號(hào)的結(jié)果集 注意:1.子查詢必須的別名 2.必須為子查詢中所有字段命名,也就意味著需要為新生成的行號(hào)列命名

      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()實(shí)現(xiàn)分頁

      --1.先寫出有行號(hào)的結(jié)果集

      select ROW_NUMBER() over(order by studentno),* from Student

      --2.查詢有行號(hào)的結(jié)果集 子查詢做為結(jié)果集必須添加別名,子查詢的列必須都有名稱

      select * from (select ROW_NUMBER() over(order by studentno) id,* from Student) temp where id>0 and id<=5

      --查詢年齡比“廖楊”大的學(xué)員,顯示這些學(xué)員的信息

      select * from Student where BornDate<(select BornDate from Student where StudentName='廖楊')

      --查詢二期班開設(shè)的課程

      select * from Subject where ClassId=(select ClassId from grade where classname='二期班')

      --查詢參加最近一次“office”考試成績最高分和最低分

      --1查詢出科目 ID

      select subjectid from Subject where SubjectName='office'

      --2.查詢出這一科目的考試日期

      select MAX(ExamDate) from Result where SubjectId=(select subjectid from Subject where SubjectName='office')

      --3,寫出查詢的框架

      select MAX(StudentResult),MIN(StudentResult) from Result where SubjectId=() and ExamDate=()

      --4.使用子查詢做為條件

      select MAX(StudentResult),MIN(StudentResult) from Result where SubjectId=(

      select subjectid from Subject where SubjectName='office'

      ) and ExamDate=(

      select MAX(ExamDate) from Result where SubjectId=(

      select subjectid from Subject where SubjectName='office'

      )

      )

      16.表連接Join

      --1.inner join :能夠找到兩個(gè)表中建立連接字段值相等的記錄

      --查詢學(xué)員信息顯示班級(jí)名稱

      select Student.StudentNo,Student.StudentName,grade.classname

      from Student

      inner join grade on Student.ClassId=grade.ClassId

      --左連接: 關(guān)鍵字前面的表是左表,后面的表是右表

      --左連接可以得到左表所有數(shù)據(jù),如果建立關(guān)聯(lián)的字段值在右表中不存在,那么右表的數(shù)據(jù)就以null值替換

      select PhoneNum.*,PhoneType.*

      from PhoneNum

      left join PhoneType on PhoneNum.pTypeId=PhoneType.ptId

      --右連接: 關(guān)鍵字前面的表是左表,后面的表是右表

      --右連接可以得到右表所有數(shù)據(jù),如果建立關(guān)聯(lián)的字段值在右左表中不存在,那么左表的數(shù)據(jù)就以null值替換

      select PhoneNum.*,PhoneType.*

      from PhoneNum

      right join PhoneType on PhoneNum.pTypeId=PhoneType.ptId

      --full join :可以得到左右連接的綜合結(jié)果--去重復(fù)

      select PhoneNum.*,PhoneType.*

      from PhoneNum

      full join PhoneType on PhoneNum.pTypeId=PhoneType.ptId

      17.事務(wù)

      一種處理機(jī)制。以事務(wù)處理的操作,要么都能成功執(zhí)行,要么都不執(zhí)行

      事務(wù)的四個(gè)特點(diǎn) ACID:

      A:原子性:事務(wù)必須是原子工作單元;對(duì)于其數(shù)據(jù)修改,要么全都執(zhí)行,要么全都不執(zhí)行。它是一個(gè)整體,不能再拆分

      C:一致性:事務(wù)在完成時(shí),必須使所有的數(shù)據(jù)都保持一致狀態(tài)。。某種程度的一致

      I:隔離性:事務(wù)中隔離,每一個(gè)事務(wù)是單獨(dú)的請(qǐng)求將單獨(dú)的處理,與其它事務(wù)沒有關(guān)系,互不影響

      D:持久性:如果事務(wù)一旦提交,就對(duì)數(shù)據(jù)的修改永久保留

      使用事務(wù):

      將你需要操作的sql命令包含在事務(wù)中

      1.在事務(wù)的開啟和事務(wù)的提交之間

      2.在事務(wù)的開啟和事務(wù)的回滾之間

      三個(gè)關(guān)鍵語句:

      開啟事務(wù):begin transaction

      提交事務(wù):commit transaction

      回滾事務(wù):rollback transaction

      declare @num int =0 --記錄操作過程中可能出現(xiàn)的錯(cuò)誤號(hào)

      begin transaction

      update bank set cmoney=cmoney-500 where name='aa'

      set @num=@num @@ERROR

      --說明這一句的執(zhí)行有錯(cuò)誤 但是不能在語句執(zhí)行的過程中進(jìn)行提交或者回滾

      --語句塊是一個(gè)整體,如果其中一句進(jìn)行了提交或者回滾,那么后面的語句就不再屬于當(dāng)前事務(wù),

      --事務(wù)不能控制后面的語句的執(zhí)行

      update bank set cmoney=cmoney 500 where name='bb'

      set @num=@num @@ERROR

      select * from bank

      if(@num<>0 ) --這個(gè)@@ERROR只能得到最近一一條sql語句的錯(cuò)誤號(hào)

      begin

      print '操作過程中有錯(cuò)誤,操作將回滾'

      rollback transaction

      end

      else

      begin

      print '操作成功'

      commit transaction

      end

      --事務(wù)一旦開啟,就必須提交或者回滾

      --事務(wù)如果有提交或者回滾,必須保證它已經(jīng)開啟

      18.視圖

      視圖就是一張?zhí)摂M表,可以像使用子查詢做為結(jié)果集一樣使用視圖

      select * from vw_getinfo

      使用代碼創(chuàng)建視圖

      語法:

      create view vw_自定義名稱

      as

      查詢命令

      go

      --查詢所有學(xué)員信息

      if exists(select * from sysobjects where name='vw_getAllStuInfo')

      drop view vw_getAllStuInfo

      go --上一個(gè)批處理結(jié)果的標(biāo)記

      create view vw_getAllStuInfo

      as

      --可以通過聚合函數(shù)獲取所以記錄數(shù)

      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 --只能創(chuàng)建一個(gè)查詢語句

      --delete from grade where ClassId>100 --在視圖中不能包含增加刪除修改

      go

      --使用視圖。。就像使用表一樣

      select * from vw_getAllStuInfo

      --對(duì)視圖進(jìn)行增加刪除和修改操作--可以對(duì)視圖進(jìn)行增加刪除和修改操作,只是建議不要這么做:所發(fā)可以看到:如果操作針對(duì)單個(gè)表就可以成功,但是如果 多張的數(shù)據(jù)就會(huì)報(bào)錯(cuò):不可更新,因?yàn)樾薷臅?huì)影響多個(gè)基表。

      update vw_getAllStuInfo set classname='asdas' ,studentname='aa' where studentno=1

      19.觸發(fā)器

      觸發(fā)器:執(zhí)行一個(gè)可以改變表數(shù)據(jù)的操作(增加刪除和修改),會(huì)自動(dòng)觸發(fā)另外一系列(類似于存儲(chǔ)過程中的模塊)的操作。

      語法:

      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表創(chuàng)建名稱為tr_grade_insert的觸發(fā)器,在執(zhí)行insert操作之后觸發(fā)

      as

      declare @cnt int

      set @cnt = (select count(*) from student)

      select * ,@cnt from student

      select * from grade

      go

      --觸發(fā)器不是被調(diào)用的,而是被某一個(gè)操作觸 發(fā)的,意味著執(zhí)行某一個(gè)操作就會(huì)自動(dòng)觸發(fā) 觸發(fā)器

      insert into grade values('fasdfdssa')

      ---替換觸 發(fā)器:本來需要執(zhí)行某一個(gè)操作,結(jié)果不做了,使用觸 發(fā)器中的代碼語句塊進(jìn)行替代

      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表創(chuàng)建名稱為tr_grade_insert的觸發(fā)器,在執(zhí)行insert操作之后觸發(fā)

      as

      declare @cnt int

      set @cnt = (select count(*) from student)

      select * ,@cnt from student

      select * from grade

      go

      insert into grade values('aaaaaaaaaaaa')

      go

      ---觸 發(fā)器的兩個(gè)臨時(shí)表:

      --inserted: 操作之后的新表:所有新表與原始的物理表沒有關(guān)系,只與當(dāng)前操作的數(shù)據(jù)有關(guān)

      --deleted:操作之前的舊表:所有新表與原始的物理表沒有關(guān)系,只與當(dāng)前操作的數(shù)據(jù)有關(guān)

      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 '操作之前的表:操作之前,這一條記錄還沒有插入,所以沒有數(shù)據(jù)'

      select * from deleted

      print '操作之后的表:已經(jīng)成功插入一條記錄,所有新表中有一條記錄'

      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 '操作之前的表:存儲(chǔ)與這個(gè)修改操作相關(guān)的沒有被修改之前的記錄'

      select * from deleted

      print '操作之后的表:存儲(chǔ)這個(gè)操作相關(guān)的被修改之后 記錄'

      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 '操作之前的表:存儲(chǔ)與這個(gè)修改操作相關(guān)的沒有被刪除之前的記錄'

      select * from deleted

      print '操作之后的表:存儲(chǔ)這個(gè)操作相關(guān)的被刪除之后 記錄--沒有記錄'

      select * from inserted

      go

      --測試

      delete from grade where ClassId>15

      20.存儲(chǔ)過程

      存儲(chǔ)過程就相當(dāng)于c#中的方法

      參數(shù),返回值,參數(shù)默認(rèn)值,參數(shù):值的方式調(diào)用

      在調(diào)用的時(shí)候有三個(gè)對(duì)應(yīng):類型對(duì)應(yīng),數(shù)量對(duì)應(yīng),順序?qū)?yīng)

      創(chuàng)建語法:

      create proc usp_用戶自定義名稱

      對(duì)應(yīng)方法的形參 –(int age, out string name)

      as

      對(duì)應(yīng)方法體:創(chuàng)建變量,邏輯語句,增加刪除修改和查詢..return返回值

      go

      調(diào)用語法:

      exec 存儲(chǔ)過程名稱 實(shí)參,實(shí)參,實(shí)參 …

      --獲取所有學(xué)員信息

      if exists(select * from sysobjects where name='usp_getAllStuInfo')

      drop proc usp_getAllStuInfo

      go

      create procedure usp_getAllStuInfo

      as

      select * from Student

      go

      --調(diào)用存儲(chǔ)過程,獲取的有學(xué)員信息

      execute usp_getAllStuInfo

      --exec sp_executesql 'select * from Student'

      --查詢指定性別的學(xué)員信息

      go

      if exists(select * from sysobjects where name='usp_getAllStuInfoBySex')

      drop proc usp_getAllStuInfoBySex

      go

      create procedure usp_getAllStuInfoBySex

      @sex nchar(1) --性別 參數(shù)不需要declare

      as

      select * from Student where Sex=@sex

      go

      --調(diào)用存儲(chǔ)過程,獲取指定性別的學(xué)員信息

      Exec usp_getAllStuInfoBySex '女'

      --創(chuàng)建存儲(chǔ)過程獲取指定班級(jí)和性別的學(xué)員信息

      go

      if exists(select * from sysobjects where name='usp_getAllStuInfoBySexandClassName')

      drop proc usp_getAllStuInfoBySexandClassName

      go

      create procedure usp_getAllStuInfoBySexandClassName

      @classname nvarchar(50), --班級(jí)名稱

      @sex nchar(1)='男'--性別 有默認(rèn)的參數(shù)建議寫在參數(shù)列表的最后

      as

      declare @classid int ---班級(jí)ID

      set @classid=(select classid from grade where classname=@classname) --通過參數(shù)班級(jí)名稱獲取對(duì)應(yīng)的班級(jí)ID

      select * from Student where Sex=@sex and ClassId=@classid

      go

      --執(zhí)行存儲(chǔ)過程獲取指定班級(jí)和性別的學(xué)員信息

      --exec usp_getAllStuInfoBySexandClassName '八期班'

      exec usp_getAllStuInfoBySexandClassName default, '八期班' --有默認(rèn)值的參數(shù)可以傳遞default

      exec usp_getAllStuInfoBySexandClassName @classname='八期班' --也可以通過參數(shù)=值的方式調(diào)用

      exec usp_getAllStuInfoBySexandClassName @classname='八期班' ,@sex='女'

      exec usp_getAllStuInfoBySexandClassName @classname='八期班',@sex='女'

      --創(chuàng)建存儲(chǔ)過程,獲取指定性別的學(xué)員人數(shù)及總?cè)藬?shù)

      go

      if exists(select * from sysobjects where name='usp_getCountBySexandClassName')

      drop proc usp_getCountBySexandClassName

      go

      create procedure usp_getCountBySexandClassName

      @cnt int=100 output, --output標(biāo)記說明它是一個(gè)輸出參數(shù)。output意味著你向服務(wù)器請(qǐng)求這個(gè)參數(shù)的值,那么在執(zhí)行的時(shí)候,服務(wù)器發(fā)現(xiàn)這個(gè)參數(shù)標(biāo)記了output,就會(huì)將這個(gè)參數(shù)的值返回輸出

      @totalnum int =200output, --總?cè)藬?shù)

      @className nvarchar(50), --輸入?yún)?shù)沒有默認(rèn)值,在調(diào)用的時(shí)候必須傳入值

      @sex nchar(1)='男'--輸入?yún)?shù)有默認(rèn)值,用戶可以選擇是否傳入值

      as

      declare @classid int ---班級(jí)ID

      set @classid=(select classid from grade where classname=@classname) --通過參數(shù)班級(jí)名稱獲取對(duì)應(yīng)的班級(jí)ID

      select * from Student where Sex=@sex and ClassId=@classid

      set @cnt= (select COUNT(*) from Student where Sex=@sex and ClassId=@classid) --獲取指定班級(jí)和性別的總?cè)藬?shù)

      set @totalnum=(select COUNT(*) from Student) ----獲取總?cè)藬?shù)

      go

      --調(diào)用存儲(chǔ)過程,獲取指定性別的學(xué)員人數(shù)及總?cè)藬?shù)

      declare @num int,@tnum int

      exec usp_getCountBySexandClassName @cnt=@num output ,@totalnum=@tnum output , @className='八期班'

      print @num

      print @tnum

      print '做完了'

      ---獲取指定班級(jí)的人數(shù)

      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整數(shù)值

      --return '總?cè)藬?shù)是' cast(@cnt as varchar(2))

      return @cnt

      go

      --調(diào)用存儲(chǔ)過程,接收存儲(chǔ)過程的返回值

      declare @count int

      --set @count=(exec usp_getCount)

      exec @count=usp_getCount '八期班'

      print @count

      if exists(select * from sysobjects where name='usp_getClassList')

      drop proc usp_getClassList

      go

      create procedure usp_getClassList

      as

      select classid,classname from grade

      go

      21.分頁存儲(chǔ)過程

      if exists(select * from sysobjects where name='usp_getPageData')

      drop proc usp_getPageData

      go

      create procedure usp_getPageData

      @totalPage int output,--總頁數(shù)

      @pageIndex int =1 ,--當(dāng)前頁碼,默認(rèn)是第一頁

      @pageCount int =5 --每一頁顯示的記錄數(shù)

      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)

      --如果是先創(chuàng)建主鍵再創(chuàng)建聚集索引就不可以,因?yàn)橹麈I默認(rèn)就是聚集索引

      --但是如果先創(chuàng)建聚集索引,那么還可以再創(chuàng)建主鍵,因?yàn)橹麈I不一定需要是聚集的

      23.臨時(shí)表

      --創(chuàng)建局部臨時(shí)表

      create table #newGrade

      (

      classid int ,

      classname nvarchar(50)

      )

      ---局部臨時(shí)表只有在當(dāng)前創(chuàng)建它的會(huì)話中使用,離開這個(gè)會(huì)話臨時(shí)表就失效.如果關(guān)閉創(chuàng)建它的會(huì)話,那么臨時(shí)表就會(huì)消失

      insert into #newGrade select * from grade

      select * from #newGrade

      select * into #newnewnew from grade

      select * into newGrade from #newgrade

      --創(chuàng)建全局臨時(shí)表:只要不關(guān)閉當(dāng)前會(huì)話,全局臨時(shí)表都可以使用,但是關(guān)閉當(dāng)前會(huì)話,全局臨時(shí)表也會(huì)消失

      create table ##newGrade

      (

      classid int ,

      classname nvarchar(50)

      )

      drop table ##newGrade

      select * into ##newGrade from grade

      select * from ##newGrade

      --創(chuàng)建表變量

      declare @tb table(cid int,cname nvarchar(50))

      insert into @tb select * from grade

      select * from @tb

        本站是提供個(gè)人知識(shí)管理的網(wǎng)絡(luò)存儲(chǔ)空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點(diǎn)。請(qǐng)注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購買等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請(qǐng)點(diǎn)擊一鍵舉報(bào)。
        轉(zhuǎn)藏 分享 獻(xiàn)花(0

        0條評(píng)論

        發(fā)表

        請(qǐng)遵守用戶 評(píng)論公約

        類似文章 更多