MSSQL复习的相关知识点有哪些
这篇文章主要介绍“MSSQL复习的相关知识点有哪些”,在日常操作中,相信很多人在MSSQL复习的相关知识点有哪些问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”MSSQL复习的相关知识点有哪些”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!
2、--判断数据库文件是否已经存在:数据库的记录都存储在master库中的sysdatabases表中--自动切换当前数据库--使用代码开启外围应该配置器execsp_configure'showadvancedoptions',1RECONFIGUREexecsp_configure'xp_cmdshell',1RECONFIGURE--自定义目录xp_cmdshell可以创建出目录'mkdirf:\project':指定创建目录execxp_cmdshell'mkdirf:\project'usemaster--exists函数判断()中的查询语句是否返回结果集,如果返回了结果集则得到true,否则得到falseifexists(select*fromsysdatabaseswherename='School')dropdatabaseSchool--删除当前指定名称的数据库createdatabaseSchoolonprimary(name='School_data',--逻辑名称.说明最多能够存储100mb数据,如果没有限制就可以将硬盘存储满size=3mb,--初始大小maxsize=100mb,--最大容量filegrowth=10%,--文件增长一次增长10%filename='f:\project\School_data.mdf'),--创建文件组filegroupmygroup(name='School_data1',--逻辑名称.说明最多能够存储100mb数据,如果没有限制就可以将硬盘存储满size=3mb,--初始大小maxsize=100mb,--最大容量filegrowth=10%,--文件增长一次增长10%filename='F:\qiyi\School_data1.ndf')logon(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、.创建数据表
语法:
create table 表名
(
字段名称 字段类型 字段特征(是否为null,默认值 标识列 主键 唯一键 外键 check约束),
字段名称 字段类型 字段特征(是否为null,默认值 标识列 主键 唯一键 外键 check约束)
)
创建老师表Teacher :Id、Name、Gender、Age、Salary、Birthday
useSchool--插入teacher所有字段的数据.如果在表后没有指定需要插入的字段名称,那么就默认为所有字段添加值--但是一定需要注意的是:标识列永远不能自定义值--不能人为插入值--仅当使用了列列表并且IDENTITY_INSERT为ON时,才能为表'Teacher'中的标识列指定显式值。insertintoTeachervalues('张三',5,1,30,4000,'1984-9-11')insertintoTeacher(Name,ClassId,Gender,Age,Salary,Birthday)values('张三',5,1,30,4000,'1984-9-11')--不为可以为null的字段插入值:可以null的字段可以不赋值--列名或所提供值的数目与表定义不匹配insertintoTeacher(Name,ClassId,Gender,Age,Salary)values('李四',5,1,30,4000)--非空字段一定需要赋值:不能将值NULL插入列'Gender',表'School.dbo.Teacher';列不允许有Null值。INSERT失败insertintoTeacher(Name,ClassId,Age,Salary)values('李四',5,30,4000)--为有默认值的字段插入值:--1.不写这一列让系统自动赋值insertintoTeacher(Name,ClassId,Gender,Age)values('王五',5,1,30)--指定null或者defaultinsertintoTeacher(Name,ClassId,Gender,Age,Salary,Birthday)values('赵六',5,1,30,default,null)--数据必须完全符合表的完整性约束insertintoTeacher(Name,ClassId,Gender,Age,Salary,Birthday)values('赵六1',5,1,300,default,null)--任意类型的数据都可以包含在''以内,不包括关键字insertintoTeacher(Name,ClassId,Gender,Age,Salary,Birthday)values('马鹏飞','5','0','15',default,null)--但是字符串值如果没有包含在''以内.会报错列名'兰鹏'无效。insertintoTeacher(Name,ClassId,Gender,Age,Salary,Birthday)values('兰鹏','5','0','15',default,null)--但是数值组成的字符串可以不使用''包含insertintoTeacher(Name,ClassId,Gender,Age,Salary,Birthday)values(123,'5','0','15',default,null)--日期值必须包含在’‘以内,否则就是默认值insertintoTeacher(Name,ClassId,Gender,Age,Salary,Birthday)values('邹元标2','5','0','15',default,'1991-9-11')
语法:
delete [from] 表名 where 条件
--select的作用--1.查询--2.输出select1+1--+是运算符,系统会自动为你做类型转换select1+'1'select'1'+1--如果+两边都是字符串,那么它就是一字符串连接符select'1'+'1'select'a'+1--可以输出多列值select1,2,34,3,545,67,567,6,7--Top、Distinctselect*fromStudent--top可以获取指定的记录数,值可以大于总记录数.但是不能是负值selecttop100*fromStudent--百分比是取ceiling()selecttop10percent*fromStudent--重复记录与原始的数据表数据无关,只与你查询的结果集有关系distinct可以去除结果集中的重复记录--结果集中每一列的值都一样selectdistinctLoginPwd,Sex,EmailfromStudentselectdistinctSexfromStudent
4、select的作用
--聚合函数:--1.对null过滤--2.都需要有一个参数--3.都是返回一个数值--sum():求和:只能对数值而言,对字符串和日期无效--avg():求平均值--count():计数:得到满足条件的记录数--max():求最大值:可以对任意类型的数据进行聚合,如果是字符串就比较拼音字母进行排序--min():求最小值--获取学员总人数selectCOUNT(*)fromStudent--查询最大年龄值selectMIN(BornDate)fromStudentselectmax(BornDate)fromStudent--查询总分selectSUM(StudentResult)fromResultwhereStudentNo=2--平均分selectavg(StudentResult)fromResultwhereSubjectId=1--注意细节:selectSUM(StudentName)fromStudentselectSUM(BornDate)fromStudentselectmin(StudentName)fromStudentselectmax(StudentName)fromStudent--查询学号,姓名,性别,年龄,电话,地址---查询女生selectStudentNo,StudentName,Sex,BornDate,AddressfromStudentwhereSex='女'andBornDate>'1990-1-1'andAddress='广州传智播客'--指定区间范围selectStudentNo,StudentName,Sex,BornDate,AddressfromStudentwhereBornDate>='1990-1-1'andBornDate<='1993-1-1'--between...and>=<=selectStudentNo,StudentName,Sex,BornDate,AddressfromStudentwhereBornDatebetween'1990-1-1'and'1993-1-1'--查询班级id1357的学员信息select*fromStudentwhereClassId=1orClassId=3orClassId=5orClassId=7--指定具体的取值范围--可以是任意类型的范围.值的类型需要一致--可以相互转换select*fromStudentwhereClassIdin(1,3,'5',7)select*fromStudentwhereClassIdnotin(1,3,'5',7)
5、聚合函数
--带条件的查询-模糊查询--只针对字符串而言--查询姓林的女生信息--=是一种精确查询,需要完全匹配select*fromStudentwhereSex='女'andStudentName='林'--通配符--元字符--%:任意个任意字段window:*正则表达式:.*--_:任意的单个字符--[]:代表一个指定的范围,范围可以是连续也可以是间断的。与正则表达式完全一样[0-9a-zA-Z].可以从这个范围中取一个字符--[^]:取反值select*fromStudentwhereSex='女'andStudentName='林%'--通配符必须在模糊查询关键的中才可以做为通配符使用,否则就是普通字符--like像。。。。一样select*fromStudentwhereSex='女'andStudentNamelike'林%'select*fromStudentwhereSex='女'andStudentNamelike'林_'--[]的使用学号在11~15之间的学员信息select*fromStudentwhereStudentNolike'[13579]'---处理null值--null:不是地址没有分配,而是不知道你需要存储什么值所以null是指不知道。但是=只能匹配具体的值,而null根本就不是一个值selectCOUNT(email)fromStudentwhereEmail!=nullselectCOUNT(email)fromStudentwhereEmailisnullselectcount(email)fromStudentwhereEmailisnotnull--将null值替换为指定的字符串值selectStudentName,ISNULL(Email,'没有填写电子邮箱')fromStudentwhereClassId=2
6、模糊查询
--当你看到每一个,,各自,不同,,分别需要考虑分组--查询每一个班级的男生人数--与聚合函数一起出现在查询中的列,要么也被聚合,要么被分组selectclassid,Sex,COUNT(*)fromStudentwhereSex='男'groupbyClassId,sex--查询每一个班级的总人数,显示人数>=2的信息--1.聚合不应出现在WHERE子句中--语法错误selectClassId,COUNT(*)asnumfromStudentwhereEmailisnotnullGROUPbyClassIdhavingCOUNT(*)>=2orderbynumdesc--完整的sql查询家庭--512346--select字段列表from表列表where数据源做筛选groupby分组字段列表having分组结果集做筛选Orderby对结果集做记录重排selectClassId,COUNT(*)asnumfromStudentwhereEmailisnotnullGROUPbyClassIdorderbyClassIddesc--关于top的执行顺序排序之后再取top值selecttop1ClassId,COUNT(*)asnumfromStudentGROUPbyClassIdorderbynumdesc7.类型转换函数
--select:输出为结果集--虚拟表--print:以文本形式输出只能输出一个字符串值.print1+'a'select1,2select*fromStudent--类型转换--Convert(目标类型,源数据,[格式])--日期有格式print'我的成绩是:'+convert(char(3),100)print'今天是个大日子:'+convert(varchar(30),getdate(),120)selectgetdate()selectlen(getdate())--cast(源数据as目标类型)它没有格式print'我的成绩是:'+cast(100aschar(3))8.日期函数
--getdate():获取当前服务器日期selectGETDATE()--可以在源日期值是追加指定时间间隔的日期数selectDATEADD(dd,-90,GETDATE())--dateDiff:找到两个日期之间指定格式的差异值selectStudentName,DATEDIFF(yyyy,getdate(),BornDate)asagefromStudentorderbyage--DATENAME:可以获取日期的指定格式的字符串表现形式selectDATENAME(dw,getdate())--DATEPART:可以获取指定的日期部分selectcast(DATEPART(yyyy,getdate())asCHAR(4))+'-'+cast(DATEPART(mm,getdate())asCHAR(2))+'-'+cast(DATEPART(dd,getdate())asCHAR(2))9.数学函数
--rand:随机数:返回0到1之间的数,理论上说可以返回0但是不能返回1selectRAND()--abs:absolute:取绝对值selectABS(-100)--ceiling:获取比当前数大的最小整数selectCEILING(1.00)--floor:获取比当前数小的最大整数selectfloor(1.99999)power:selectPOWER(3,4)--round():四舍五入.只关注指定位数后一位selectROUND(1.549,1)--sign:正数==1负数==-10=0selectSIGN(-100)selectceiling(17*1.0/5)10.字符串函数
--1.CHARINDEX--IndexOf():能够返回一个字符串在源字符串的起始位置。找不到就返回0,如果可以找到就返回从1开始的索引--没有数组的概念--第一个参数是指需要查询的字符串,第二个是源字符串,第三个参数是指从源字符的那个索引位置开始查找selectCHARINDEX('人民','中华人民共和国人民',4)--LEN():可以返回指定字符串的字符个数selectLEN('中华人民共和国')--UPPER():小写字母转换为大写字母LOWER():大写转小写selectLOWER(UPPER('sadfasdfa'))--LTRIM:去除左空格RTIRM:去除右空格selectlTRIM(RTRIM('sdfsd'))+'a'--RIGHT:可以从字符串右边开始截取指定位数的字符串如果数值走出范围,不会报错,只会返回所有字符串值,但是不能是负值selectRIGHT('中华人民共和国',40)selectLEFT('中华人民共和国',2)--SUBSTRING()selectSUBSTRING('中华人民共和国',3,2)--REPLACE第一个参数是源字符串,第二个参数是需要替换的字符串,第三个参数是需要替换为什么selectREPLACE('中华人民共和国','人民','居民')selectREPLACE('中华人民共和国','','')--STUFF:将源字符串中从第几个开始,一共几个字符串替换为指定的字符串selectSTUFF('中华人民共和国',3,2,'你懂的')--sudyfsagfyas@12fasdf6.fsadfdsafdeclare@emailvarchar(50)='sudyfsagfyas@12fasdf6.fsadfdsaf'selectCHARINDEX('@',@email)selectLEFT(@email,CHARINDEX('@',@email)-1)--使用rightselectright(@email,len(@email)-CHARINDEX('@',@email))--使用substringselectSUBSTRING(@email,CHARINDEX('@',@email)+1,LEN(@email))--使用stuffselectSTUFF(@email,1,CHARINDEX('@',@email),'')11.联合结果集union
--联合结果集unionselect*fromStudentwhereSex='男'--unionselect*fromStudentwhereSex='女'--联合的前提是:--1.列的数量需要一致:使用UNION、INTERSECT或EXCEPT运算符合并的所有查询必须在其目标列表中有相同数目的表达式--2.列的类型需要可以相互转换selectStudentName,SexfromStudent--在字符串排序的时候,空格是最小的,排列在最前面unionselectcast(ClassIdasCHAR(3)),classnamefromgrade--union和unionall的区别--union是去除重复记录的--unionall不去除重复:效率更高,因为不需要判断记录是否重复,也没有必须在结果庥是执行去除重复记录的操作。但是可以需要消耗更多的内存存储空间select*fromStudentwhereClassId=2unionallselect*fromStudentwhereClassId=2--查询office这科目的全体学员的成绩,同时在最后显示它的平均分,最高分,最低分select''+cast(StudentNoasCHAR(3)),cast(SubjectIdasCHAR(2)),StudentResultfromResultwhereSubjectId=1unionselect'1','平均分',AVG(StudentResult)fromResultwhereSubjectId=1unionselect'1','最高分',max(StudentResult)fromResultwhereSubjectId=1unionselect'1','最低分',min(StudentResult)fromResultwhereSubjectId=1--一次性插入多条数据--1.先将数据复制到另外一个新表中,删除源数据表,再将新表的数据插入到源数据表中--1.select*/字段into新表from源表--1.新表是系统自动生成的,不能人为创建,如果新表名称已经存在就报错--2.新表的表结构与查询语句所获取的列一致,但是列的属性消失,只保留非空和标识列。其它全部消失,如主键,唯一键,关系,约束,默认值select*intonewGradefromgradetruncatetablegradeselect*fromnewGrade--select*intogradefromnewGrade--2.insertinto目标表select字段列表/*from数据源表--1、目标表必须先存在,如果没有就报错--2.查询的数据必须符合目标表的数据完整性--3.查询的数据列的数量和类型必须的目标的列的数量和对象完全对应insertintogradeselectclassnamefromnewGradedeletefromadmin--使用union一次性插入多条记录--insertinto表(字段列表)--select值。。。。用户自定义数据--union--select值。。。。insertintoAdminselect'a','a'unionallselect'a','a'unionallselect'a','a'unionallselect'a',null12.CASE函数用法
相当于switch case---c#中的switch...case只能做等值判断
这可以对字段值或者表达式进行判断,返回一个用户自定义的值,它会生成一个新列
2.要求then后面数据的类型一致
1.第一种做等值判断的case..end
case 字段或者表达式
when .值..then .自定义值
when .值..then .自定义值
.....
else 如果不满足上面所有的when就满足这个else
end
--显示具体班级的名称selectStudentNo,StudentName,caseClassId--如果case后面接有表达式或者字段,那么这种结构就只能做等值判断,真的相当于switch..casewhen1then'一班'when2then'2班'when3then'3班'whennullthen'aa'--不能判断null值else'搞不清白'end,sexfromStudent--2.做范围判断,相当于if..else,它可以做null值判断--case--如果没有表达式或者字段就可实现范围判断--when表达式then值--不要求表达式对同一字段进行判断--when表达式then值--.....--else其它情况--endselectStudentNo,StudentName,casewhenBornDate>'2000-1-1'then'小屁孩'whenBornDate>'1990-1-1'then'小青年'whenBornDate>'1980-1-1'then'青年'--whenSex='女'then'是女的'whenBornDateisnullthen'出生不详'else'中年'endfromStudent--百分制转换为素质教育90-A80--B70--C60--D<60ENULL--没有参加考试selectStudentNo,SubjectId,casewhenStudentResult>=90then'A'whenStudentResult>=80then'B'whenStudentResult>=70then'C'whenStudentResult>=60then'D'whenStudentResultisnullthen'没有参加考试'else'E'end成绩,ExamDatefromResult13.IF ELSE语法
1,.没有{},使用begin..end.如果后面只有一句,可以不使用begin..end包含
2.没有bool值,只能使用关系运算符表达式
3.也可以嵌套和多重
4.if后面的()可以省略
declare@subjectnamenvarchar(50)='office'--科目名称declare@subjectIdint=(selectSubjectidfromSubjectwhereSubjectName=@subjectname)--科目IDdeclare@avgint--平均分set@avg=(selectAVG(StudentResult)fromResultwhereSubjectId=@subjectIdandStudentResultisnotnull)--获取平均分print@avgif@avg>=60beginprint'成绩不错,输出前三名:'selecttop3*fromResultwhereSubjectId=@subjectIdorderbyStudentResultdescendelsebeginprint'成绩不好,输出后三名:'selecttop3*fromResultwhereSubjectId=@subjectIdorderbyStudentResultend14.WHILE循环语法
没有{},使用begin..end
没有bool值,需要使用条件表达式
可以嵌套
也可以使用break,continue
godeclare@subjectNamenvarchar(50)='office'--科目名称declare@subjectIdint--科目IDdeclare@classidint=(selectclassidfromSubjectwhereSubjectName=@subjectName)--查询当前科目属于那一个班级set@subjectId=(selectSubjectIdfromSubjectwhereSubjectName=@subjectName)--获取科目IDdeclare@totalCountint--总人数:那一个班级需要考试这一科目set@totalCount=(selectCOUNT(*)fromStudentwhereClassId=@classid)print@totalcount--14declare@unpassNumint--不及格人数set@unpassNum=(selectCOUNT(distinctStudentno)fromResultwhereSubjectId=@subjectIdandStudentNoin(selectStudentNofromStudentwhereClassId=@classid)andStudentResult<60)while(@unpassNum>@totalCount/2)begin--执行循环加分updateResultsetStudentResult+=2whereSubjectId=@subjectIdandStudentNoin(selectStudentNofromStudentwhereClassId=@classid)andStudentResult<=98--重新计算不及格人数set@unpassNum=(selectCOUNT(distinctStudentno)fromResultwhereSubjectId=@subjectIdandStudentNoin(selectStudentNofromStudentwhereClassId=@classid)andStudentResult<60)endgodeclare@subjectNamenvarchar(50)='office'--科目名称declare@subjectIdint--科目IDdeclare@classidint=(selectclassidfromSubjectwhereSubjectName=@subjectName)--查询当前科目属于那一个班级set@subjectId=(selectSubjectIdfromSubjectwhereSubjectName=@subjectName)--获取科目IDdeclare@totalCountint--总人数set@totalCount=(selectCOUNT(*)fromStudentwhereClassId=@classid)print@totalcount--14declare@unpassNumint--不及格人数while(1=1)beginset@unpassNum=(selectCOUNT(distinctStudentno)fromResultwhereSubjectId=@subjectIdandStudentNoin(selectStudentNofromStudentwhereClassId=@classid)andStudentResult<60)if(@unpassNum>@totalCount/2)updateResultsetStudentResult+=2whereSubjectId=@subjectIdandStudentNoin(selectStudentNofromStudentwhereClassId=@classid)andStudentResult<=98elsebreakend15.子查询
子查询--一个查询中包含另外一个查询。被包含的查询就称为子查询,。包含它的查询就称父查询
1.子查询的使用方式:使用()包含子查询
2.子查询分类:
1.独立子查询:子查询可以直接独立运行
查询比“王八”年龄大的学员信息
select * from Student where BornDate<(select BornDate from Student where StudentName='王八')
2.相关子查询:子查询使用了父查询中的结果
--子查询的三种使用方式--1.子查询做为条件,子查询接在关系运算符后面><>=<==<>!=,如果是接这关系运算符后面,必须保证子查询只返回一个值--查询六期班的学员信息select*fromStudentwhereClassId=(selectClassIdfromgradewhereclassname='八期班')--子查询返回的值不止一个。当子查询跟随在=、!=、<、<=、>、>=之后,或子查询用作表达式时,这种情况是不允许的。select*fromStudentwhereClassId=(selectClassIdfromgrade)--查询八期班以外的学员信息--当子查询返回多个值(多行一列),可以使用in来指定这个范围select*fromStudentwhereClassIdin(selectClassIdfromgradewhereclassname<>'八期班')--当没有用EXISTS引入子查询时,在选择列表中只能指定一个表达式。如果是多行多列或者一行多列就需要使用exists--使用EXISTS关键字引入子查询后,子查询的作用就相当于进行存在测试。外部查询的WHERE子句测试子查询返回的行是否存在select*fromStudentwhereEXISTS(select*fromgrade)select*fromStudentwhereClassIdin(select*fromgrade)--2.子查询做为结果集--selecttop5*fromStudent--前五条--使用top分页selecttop5*fromStudentwhereStudentNonotin(selecttop5studentnofromStudent)--使用函数分页ROW_NUMBER()over(orderbystudentno),可以生成行号,排序的原因是因为不同的排序方式获取的记录顺序不一样selectROW_NUMBER()over(orderbystudentno),*fromStudent--查询拥有新生成行号的结果集注意:1.子查询必须的别名2.必须为子查询中所有字段命名,也就意味着需要为新生成的行号列命名select*from(selectROW_NUMBER()over(orderbystudentno)id,*fromStudent)tempwheretemp.id>0andtemp.id<=5select*from(selectROW_NUMBER()over(orderbystudentno)id,*fromStudent)tempwheretemp.id>5andtemp.id<=10select*from(selectROW_NUMBER()over(orderbystudentno)id,*fromStudent)tempwheretemp.id>10andtemp.id<=15--3.子查询还可以做为列的值select(selectstudentnamefromstudentwherestudentno=result.studentno),(selectsubjectnamefromsubjectwheresubjectid=result.SubjectId),StudentResultfromResult--使用Row_numberover()实现分页--1.先写出有行号的结果集selectROW_NUMBER()over(orderbystudentno),*fromStudent--2.查询有行号的结果集子查询做为结果集必须添加别名,子查询的列必须都有名称select*from(selectROW_NUMBER()over(orderbystudentno)id,*fromStudent)tempwhereid>0andid<=5--查询年龄比“廖杨”大的学员,显示这些学员的信息select*fromStudentwhereBornDate<(selectBornDatefromStudentwhereStudentName='廖杨')--查询二期班开设的课程select*fromSubjectwhereClassId=(selectClassIdfromgradewhereclassname='二期班')--查询参加最近一次“office”考试成绩最高分和最低分--1查询出科目IDselectsubjectidfromSubjectwhereSubjectName='office'--2.查询出这一科目的考试日期selectMAX(ExamDate)fromResultwhereSubjectId=(selectsubjectidfromSubjectwhereSubjectName='office')--3,写出查询的框架selectMAX(StudentResult),MIN(StudentResult)fromResultwhereSubjectId=()andExamDate=()--4.使用子查询做为条件selectMAX(StudentResult),MIN(StudentResult)fromResultwhereSubjectId=(selectsubjectidfromSubjectwhereSubjectName='office')andExamDate=(selectMAX(ExamDate)fromResultwhereSubjectId=(selectsubjectidfromSubjectwhereSubjectName='office'))16.表连接Join
--1.innerjoin:能够找到两个表中建立连接字段值相等的记录--查询学员信息显示班级名称selectStudent.StudentNo,Student.StudentName,grade.classnamefromStudentinnerjoingradeonStudent.ClassId=grade.ClassId
--左连接:关键字前面的表是左表,后面的表是右表--左连接可以得到左表所有数据,如果建立关联的字段值在右表中不存在,那么右表的数据就以null值替换selectPhoneNum.*,PhoneType.*fromPhoneNumleftjoinPhoneTypeonPhoneNum.pTypeId=PhoneType.ptId
--右连接:关键字前面的表是左表,后面的表是右表--右连接可以得到右表所有数据,如果建立关联的字段值在右左表中不存在,那么左表的数据就以null值替换selectPhoneNum.*,PhoneType.*fromPhoneNumrightjoinPhoneTypeonPhoneNum.pTypeId=PhoneType.ptId
--fulljoin:可以得到左右连接的综合结果--去重复selectPhoneNum.*,PhoneType.*fromPhoneNumfulljoinPhoneTypeonPhoneNum.pTypeId=PhoneType.ptId17.事务
一种处理机制。以事务处理的操作,要么都能成功执行,要么都不执行
事务的四个特点 ACID:
A:原子性:事务必须是原子工作单元;对于其数据修改,要么全都执行,要么全都不执行。它是一个整体,不能再拆分
C:一致性:事务在完成时,必须使所有的数据都保持一致状态。。某种程度的一致
I:隔离性:事务中隔离,每一个事务是单独的请求将单独的处理,与其它事务没有关系,互不影响
D:持久性:如果事务一旦提交,就对数据的修改永久保留使用事务:
将你需要操作的sql命令包含在事务中
1.在事务的开启和事务的提交之间
2.在事务的开启和事务的回滚之间
三个关键语句:
开启事务:begin transaction
提交事务:commit transaction
回滚事务:rollback transaction
declare@numint=0--记录操作过程中可能出现的错误号begintransactionupdatebanksetcmoney=cmoney-500wherename='aa'set@num=@num+@@ERROR--说明这一句的执行有错误但是不能在语句执行的过程中进行提交或者回滚--语句块是一个整体,如果其中一句进行了提交或者回滚,那么后面的语句就不再属于当前事务,--事务不能控制后面的语句的执行updatebanksetcmoney=cmoney+500wherename='bb'set@num=@num+@@ERRORselect*frombankif(@num<>0)--这个@@ERROR只能得到最近一一条sql语句的错误号beginprint'操作过程中有错误,操作将回滚'rollbacktransactionendelsebeginprint'操作成功'committransactionend--事务一旦开启,就必须提交或者回滚--事务如果有提交或者回滚,必须保证它已经开启
回到顶部
18.视图视图就是一张虚拟表,可以像使用子查询做为结果集一样使用视图
select * from vw_getinfo
使用代码创建视图
语法:
create view vw_自定义名称
as
查询命令
go
--查询所有学员信息ifexists(select*fromsysobjectswherename='vw_getAllStuInfo')dropviewvw_getAllStuInfogo--上一个批处理结果的标记createviewvw_getAllStuInfoas--可以通过聚合函数获取所以记录数selecttop(selectCOUNT(*)fromStudent)Student.StudentNo,Student.StudentName,grade.ClassId,grade.classnamefromStudentinnerjoingradeonStudent.ClassId=grade.ClassIdorderbyStudentName--视图中不能使用orderby--select*fromgrade--只能创建一个查询语句--deletefromgradewhereClassId>100--在视图中不能包含增加删除修改go--使用视图。。就像使用表一样select*fromvw_getAllStuInfo--对视图进行增加删除和修改操作--可以对视图进行增加删除和修改操作,只是建议不要这么做:所发可以看到:如果操作针对单个表就可以成功,但是如果多张的数据就会报错:不可更新,因为修改会影响多个基表。updatevw_getAllStuInfosetclassname='asdas',studentname='aa'wherestudentno=119.触发器
触发器:执行一个可以改变表数据的操作(增加删除和修改),会自动触发另外一系列(类似于存储过程中的模块)的操作。
语法:
create trigger tr_表名_操作名称
on 表名 after|instead of 操作名称
as
go
ifexists(select*fromsysobjectswherename='tr_grade_insert')droptriggertr_grade_insertgocreatetriggertr_grade_insertongradeforinsert---为grade表创建名称为tr_grade_insert的触发器,在执行insert操作之后触发asdeclare@cntintset@cnt=(selectcount(*)fromstudent)select*,@cntfromstudentselect*fromgradego--触发器不是被调用的,而是被某一个操作触发的,意味着执行某一个操作就会自动触发触发器insertintogradevalues('fasdfdssa')---替换触发器:本来需要执行某一个操作,结果不做了,使用触发器中的代码语句块进行替代ifexists(select*fromsysobjectswherename='tr_grade_insert')droptriggertr_grade_insertgocreatetriggertr_grade_insertongradeinsteadofinsert---为grade表创建名称为tr_grade_insert的触发器,在执行insert操作之后触发asdeclare@cntintset@cnt=(selectcount(*)fromstudent)select*,@cntfromstudentselect*fromgradegoinsertintogradevalues('aaaaaaaaaaaa')go---触发器的两个临时表:--inserted:操作之后的新表:所有新表与原始的物理表没有关系,只与当前操作的数据有关--deleted:操作之前的旧表:所有新表与原始的物理表没有关系,只与当前操作的数据有关ifexists(select*fromsysobjectswherename='tr_grade_insert')droptriggertr_grade_insertgocreatetriggertr_grade_insertongradeafterinsertasprint'操作之前的表:操作之前,这一条记录还没有插入,所以没有数据'select*fromdeletedprint'操作之后的表:已经成功插入一条记录,所有新表中有一条记录'select*frominsertedgo--测试:insertintogradevalues('aaaaa')ifexists(select*fromsysobjectswherename='tr_grade_update')droptriggertr_grade_updategocreatetriggertr_grade_updateongradeafterupdateasprint'操作之前的表:存储与这个修改操作相关的没有被修改之前的记录'select*fromdeletedprint'操作之后的表:存储这个操作相关的被修改之后记录'select*frominsertedgo--测试updategradesetclassname=classname+'aa'whereClassId>15ifexists(select*fromsysobjectswherename='tr_grade_delete')droptriggertr_grade_deletegocreatetriggertr_grade_deleteongradeafterdeleteasprint'操作之前的表:存储与这个修改操作相关的没有被删除之前的记录'select*fromdeletedprint'操作之后的表:存储这个操作相关的被删除之后记录--没有记录'select*frominsertedgo--测试deletefromgradewhereClassId>1520.存储过程
存储过程就相当于c#中的方法
参数,返回值,参数默认值,参数:值的方式调用
在调用的时候有三个对应:类型对应,数量对应,顺序对应
创建语法:
create proc usp_用户自定义名称
对应方法的形参 --(int age, out string name)
as
对应方法体:创建变量,逻辑语句,增加删除修改和查询..return返回值
go
调用语法:
exec 存储过程名称 实参,实参,实参 ...
--获取所有学员信息ifexists(select*fromsysobjectswherename='usp_getAllStuInfo')dropprocusp_getAllStuInfogocreateprocedureusp_getAllStuInfoasselect*fromStudentgo--调用存储过程,获取的有学员信息executeusp_getAllStuInfo--execsp_executesql'select*fromStudent'--查询指定性别的学员信息goifexists(select*fromsysobjectswherename='usp_getAllStuInfoBySex')dropprocusp_getAllStuInfoBySexgocreateprocedureusp_getAllStuInfoBySex@sexnchar(1)--性别参数不需要declareasselect*fromStudentwhereSex=@sexgo--调用存储过程,获取指定性别的学员信息Execusp_getAllStuInfoBySex'女'--创建存储过程获取指定班级和性别的学员信息goifexists(select*fromsysobjectswherename='usp_getAllStuInfoBySexandClassName')dropprocusp_getAllStuInfoBySexandClassNamegocreateprocedureusp_getAllStuInfoBySexandClassName@classnamenvarchar(50),--班级名称@sexnchar(1)='男'--性别有默认的参数建议写在参数列表的最后asdeclare@classidint---班级IDset@classid=(selectclassidfromgradewhereclassname=@classname)--通过参数班级名称获取对应的班级IDselect*fromStudentwhereSex=@sexandClassId=@classidgo--执行存储过程获取指定班级和性别的学员信息--execusp_getAllStuInfoBySexandClassName'八期班'execusp_getAllStuInfoBySexandClassNamedefault,'八期班'--有默认值的参数可以传递defaultexecusp_getAllStuInfoBySexandClassName@classname='八期班'--也可以通过参数=值的方式调用execusp_getAllStuInfoBySexandClassName@classname='八期班',@sex='女'execusp_getAllStuInfoBySexandClassName@classname='八期班',@sex='女'--创建存储过程,获取指定性别的学员人数及总人数goifexists(select*fromsysobjectswherename='usp_getCountBySexandClassName')dropprocusp_getCountBySexandClassNamegocreateprocedureusp_getCountBySexandClassName@cntint=100output,--output标记说明它是一个输出参数。output意味着你向服务器请求这个参数的值,那么在执行的时候,服务器发现这个参数标记了output,就会将这个参数的值返回输出@totalnumint=200output,--总人数@classNamenvarchar(50),--输入参数没有默认值,在调用的时候必须传入值@sexnchar(1)='男'--输入参数有默认值,用户可以选择是否传入值asdeclare@classidint---班级IDset@classid=(selectclassidfromgradewhereclassname=@classname)--通过参数班级名称获取对应的班级IDselect*fromStudentwhereSex=@sexandClassId=@classidset@cnt=(selectCOUNT(*)fromStudentwhereSex=@sexandClassId=@classid)--获取指定班级和性别的总人数set@totalnum=(selectCOUNT(*)fromStudent)----获取总人数go--调用存储过程,获取指定性别的学员人数及总人数declare@numint,@tnumintexecusp_getCountBySexandClassName@cnt=@numoutput,@totalnum=@tnumoutput,@className='八期班'print@numprint@tnumprint'做完了'---获取指定班级的人数ifexists(select*fromsysobjectswherename='usp_getCount')dropprocusp_getCountgocreateprocedureusp_getCount@classNamenvarchar(50)='八期班'asdeclare@classidint=(selectclassidfromgradewhereclassname=@className)declare@cntintset@cnt=(selectCOUNT(*)fromStudentwhereClassId=@classid)--return只能返回int整数值--return'总人数是'+cast(@cntasvarchar(2))return@cntgo--调用存储过程,接收存储过程的返回值declare@countint--set@count=(execusp_getCount)exec@count=usp_getCount'八期班'print@countifexists(select*fromsysobjectswherename='usp_getClassList')dropprocusp_getClassListgocreateprocedureusp_getClassListasselectclassid,classnamefromgradego21.分页存储过程
ifexists(select*fromsysobjectswherename='usp_getPageData')dropprocusp_getPageDatagocreateprocedureusp_getPageData@totalPageintoutput,--总页数@pageIndexint=1,--当前页码,默认是第一页@pageCountint=5--每一页显示的记录数asselect*from(selectROW_NUMBER()over(orderbystudentno)id,*fromStudent)tempwheretemp.id>(@pageindex-1)*@pagecountandtemp.id<=(@pageindex*@pagecount)set@totalPage=CEILING((selectCOUNT(*)fromStudent)*1.0/@pageCount)go22.索引
select*fromsysindexes--createindexIX_Student_studentName--on表名(字段名)--clusteredindex:聚集索引nonclusteredindex--非聚集索引ifexists(select*fromsysindexeswherename='IX_Student_studentName')dropindexstudent.IX_Student_studentNamegocreateclusteredindexIX_Student_studentNameonstudent(studentname)--如果是先创建主键再创建聚集索引就不可以,因为主键默认就是聚集索引--但是如果先创建聚集索引,那么还可以再创建主键,因为主键不一定需要是聚集的23.临时表
--创建局部临时表createtable#newGrade(classidint,classnamenvarchar(50))---局部临时表只有在当前创建它的会话中使用,离开这个会话临时表就失效.如果关闭创建它的会话,那么临时表就会消失insertinto#newGradeselect*fromgradeselect*from#newGradeselect*into#newnewnewfromgradeselect*intonewGradefrom#newgrade--创建全局临时表:只要不关闭当前会话,全局临时表都可以使用,但是关闭当前会话,全局临时表也会消失createtable##newGrade(classidint,classnamenvarchar(50))droptable##newGradeselect*into##newGradefromgradeselect*from##newGrade--创建表变量declare@tbtable(cidint,cnamenvarchar(50))insertinto@tbselect*fromgradeselect*from@tb
到此,关于“MSSQL复习的相关知识点有哪些”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。