1 --------------------------------------------------------SQL基本命令開始------------------------------------------------------- 2 3 --切換數據庫 4 use master 5 go 6 7 ---------------------------------------數據庫操作----------------------------------------------------------------- 8 --刪除數據庫 9 --drop DataBase MySchool 10 11 -- 創建數據庫 12 create database MySchool 13 on 14 ( 15 name="MySchool", --文件的邏輯名 16 filename="d:\database\MySchool.mdf", --文件的保存路徑,database文件夾要先存在 17 size=3, --文件的初始大小 18 maxsize=100, --文件的最大值 19 filegrowth=1 --文件的增長比例,還可以filegrowth=10% 20 ) 21 --日志文件 22 log on 23 ( 24 name="MySchool_log", --文件的邏輯名 25 filename="d:\database\MySchool_ldf.ldf", --文件的保存路徑,database文件夾要先存在 26 size=3, --文件的初始大小 27 maxsize=100, --文件的最大值 28 filegrowth=10% --文件的增長比例,還可以filegrowth=10% 29 30 ) 31 go 32 --修改數據庫 33 --alter database MySchool 34 35 36 --------------------------------------------數據庫操作結束-------------------------------------------------------------------- 37 38 39 40 --------------------------------------------表操作---------------------------------------------------------------------------- 41 42 --注意,當刪除表時,如果表上有外鍵約束,應注意刪除順序,還有就是級聯刪除,不再累贅 43 --切換數據庫 44 use MySchool 45 go 46 --刪除表 47 --drop table Class 48 --創建表 Class 49 create table Class 50 ( 51 cId int identity(1,1) primary key,--設置cId為自動增長,初始值為1,增長量為1,並且為主鍵 52 cName nvarchar(10) not null, 53 cDescription nvarchar(200) 54 ) 55 go 56 --刪除表Student 57 --drop table Student 58 --創建表 59 create table Student 60 ( 61 sId int identity(1,1) primary key,--設置sId為自動增長,初始值為1,增長量為1,並且為主鍵 62 sName nvarchar(10) not null,--設置姓名不能為空 63 sSex nchar(1) , 64 sAge int,-- check(sAge>18 and sAge<150), 65 sBirthday datetime, 66 sClassId int not null, 67 sNo decimal(18,0)--身份證號 68 ) 69 go 70 71 72 73 74 -------------------------表結構的修改------------- 75 --增加列 76 alter table Student 77 add sNo decimal(18,0) 78 79 --修改表 時要加上 column 80 alter table student 81 alter column sName nvarchar(8) 82 83 alter table student 84 alter column sName nvarchar(10) not null 85 86 87 --刪除列 時 要加column 88 alter table Student 89 drop column sNo 90 91 --刪除表Score 92 --drop table Score 93 --創建表 Score 94 create table Score 95 ( 96 sId int identity(1,1) primary key, 97 studentId int not null, 98 english float, 99 math float 100 ) 101 go 102 103 104 --插入數據到 Class,可以把列直接拖到()中 105 insert into Class (cName)values('高一一班') 106 insert into Class (cName, cDescription)values('高一二班','快班') 107 --insert into Class values('高一三班') --省略列名時,必須插入所有數據,自動增長列除外 108 insert into Class values('高一三班','中班') 109 --查詢數據 110 select * from Class 111 112 --插入數據到 Student 113 --insert into Student(sName, sSex, sAge, sBirthday, sClassId) values('tom','男',22,1993-02-12,1); 114 --錯誤,日期必須加引號 115 insert into Student(sName, sSex, sAge, sBirthday, sClassId) values('tom','男',22,'1993-02-12',1); 116 insert into Student(sName, sSex, sAge, sBirthday, sClassId) values('jack','男',22,'1993-02-12',1); 117 118 --修改數據 119 update Student set sAge=19,sSex='女' 120 update Student set sSex='男' where sId=1 121 update Student set sAge=sAge+1 122 123 --查詢數據 124 select * from Student 125 --刪除數據 126 delete from Student 127 delete from Student where sName='tom' 128 129 --清空表中的數據,連自動編號也一起清掉 130 truncate table Score 131 truncate table Student 132 truncate table Class 133 134 --------------------------------------------表操作結束-------------------------------------------------------------------- 135 136 137 138 139 140 ----------------------------------------------約束開始--------------------------------------------------------------------- 141 142 143 --自動增長 144 --下面的寫法太麻煩 145 --alter table Student 146 --drop column sId 147 --alter table Student 148 --add sId int identity(1,1) 149 150 --alter table Score 151 --drop column sId 152 --alter table Score 153 --add sId int identity(1,1) 154 -- 155 --alter table Class 156 --drop column cId 157 --alter table Class 158 --add cId int identity(1,1) 159 160 --非空約束-----修改表的約束 161 alter table Student 162 alter column sName nvarchar(10) not null 163 164 ------------------------給字段增加約束------------------------ 165 166 --主鍵約束 167 alter table Student 168 add constraint PK_Student_sId primary key(sId) 169 170 alter table Class 171 add constraint PK_Class_cId primary key(cId) 172 173 alter table Score 174 add constraint PK_Score_cId primary key(sId) 175 --唯一約束 176 alter table Student 177 add constraint UQ_Student_sNo unique(sNo)--身份證號唯一 178 --默認約束 179 alter table Student 180 add constraint DF_Student_sSex default('男') for sSex --注意是 for sSex 181 182 --檢查約束 183 alter table Student 184 add constraint CK_Student_sSex check(sSex='男' or sSex='女') 185 186 -------------------外鍵約束---------------------------------------- 187 188 --Score表中的外鍵是student表中的sId,student表中的外鍵是class表中的主鍵cId 189 190 --------注意 以下建立外鍵約束的順序不能反,否則會出錯 191 192 alter table Score 193 add constraint FK_Score_studentId foreign key (studentId) references Student(sId) on delete cascade on update cascade 194 195 alter table Student 196 add constraint FK_Student_sClassId foreign key (sClassId) references Class(cId) on delete cascade on update cascade --級聯刪除的實現當刪除班級號時,所在班級的所有學生的信息都被刪除. 197 198 199 200 --級聯刪除 201 --on delete cascade 202 -- on update cascade 203 204 --往子表加數據,外鍵的值必須在主表中出現 205 insert into student(sName,sNo,sClassId) values('abc',111,100) 206 --刪除主表中數據的時候,將刪除子表中外鍵對應的數據 207 delete from class where cId = 1 208 select * from class 209 select * from student 210 -------------------------------------------------約束結束---------------------------------------------------------- 211 212 ------------------------------------------------約束練習開始-------------------------------------------------------- 213 --Teacher表中 214 --tSex 控制只能是男 女,默認男 215 --tAge 在30-40之間 默認30 216 --tName 唯一 217 use master 218 go 219 create table Teacher 220 ( 221 tId int identity(1,1), 222 tSex nchar(1), 223 tAge int, 224 tName nvarchar(10) 225 ) 226 alter table Teacher 227 add constraint CK_Teacher_tSex check(tSex='男' or tSex='女') , 228 constraint DF_Teacher_tSex default ('男') for tSex, 229 constraint CK_Teacher_tAge check(tAge>=30 and tAge<=40) , 230 constraint DF_Teacher_tAge default (30) for tAge, 231 constraint UQ_Teacher_tName unique(tName) 232 ---------------------------------------練習結束結束---------------------------------------------------------------------- 233 234 ----------------------------------------約束的簡單寫法------------------------------------------------------------- 235 --drop table Student0 236 create table Student0 237 ( 238 sId int identity(1,1) primary key, 239 sName nvarchar(10) not null, 240 sAge int constraint CK_Student0_sAge check(sAge >= 18) constraint DF_Student0_sAge default(18), 241 sClassId int constraint FK_Student0_sClassId foreign key (sClassId) references Class(cId) 242 ) 243 244 245 alter table Student0 246 add sSex nchar(1) 247 248 alter table Student0 249 drop column sSex 250 251 -------------------------------------約束的簡單寫法結束--------------------------------------------------------------- 252 253 254 255 256 --------------------------------------插入測試數據開始--------------------------------------------------------------- 257 258 insert into Class (cName,cDescription) values ('高一一班','快班') 259 insert into Class (cName,cDescription) values ('高一二班','中班') 260 insert into Class (cName,cDescription) values ('高一三班','慢班') 261 insert into Class (cName,cDescription) values ('高二一班','快班') 262 insert into Class (cName,cDescription) values ('高二二班','中班') 263 insert into Class (cName,cDescription) values ('高二三班','慢班') 264 265 insert into Student (sClassId,sName,sAge,sSex,sNo,sBirthday) values (1,'劉備',20,'男',123456789012345678,'1987-5-6') 266 insert into Student (sClassId,sName,sAge,sSex,sNo,sBirthday) values (1,'關羽',19,'男',123456789012345552,'1988-8-6') 267 insert into Student (sClassId,sName,sAge,sSex,sNo,sBirthday) values (1,'張兩飛',19,'男',123456789068745672,'1989-5-19') 268 insert into Student (sClassId,sName,sAge,sSex,sNo,sBirthday) values (4,'曹操',22,'男',123456789012345673,'1985-12-6') 269 insert into Student (sClassId,sName,sAge,sSex,sNo,sBirthday) values (4,'夏侯惇',22,'男',123456789012345674,'1985-3-6') 270 insert into Student (sClassId,sName,sAge,sSex,sNo,sBirthday) values (4,'華佗',50,'男',123456789012356574,'1957-1-16') 271 insert into Student (sClassId,sName,sAge,sSex,sNo,sBirthday) values (4,'甄姬',52,'女',12345678901234565,'1989-8-8') 272 273 insert into Score (studentId,english) values(1,90) 274 insert into Score (studentId,english) values(2,90) 275 insert into Score (studentId,english) values(3,59) 276 insert into Score (studentId,english) values(4,100) 277 insert into Score (studentId,english) values(5,60) 278 insert into Score (studentId,english) values(8,0) 279 insert into Score (studentId,english) values(7,80) 280 ---------------------------------------插入測試數據結束------------------------------------------------------- 281 282 283 284 285 286 --------------------------------------數據的檢索---------------------------------------------------------------- 287 288 ------------------------------------簡單的數據檢索---------------------------------------------------------------- 289 select * from Student 290 select * from Score 291 select * from Class 292 ---------只檢索需要的列 293 select sName from student 294 select sName as '姓名',sAge as '年齡' from student 295 ----------使用where檢索符合條件的數據 296 select sName '姓名' from student where sSex='男' 297 ---------檢索不與任何表關聯的數據 298 select 1 299 select getdate() as '當前日期' 300 ---------Top 獲取前幾條數據 301 302 select top 2 * from student 303 select top 2 sName from student 304 -----使用百分號,不夠一,進一,沒有舍 305 select top 20 percent * from student 306 307 ---------Distinct 去除重復數據,是針對所有被查詢的列而言,不是單個列 308 select distinct * from student 309 select distinct sName from student 310 311 ---------------------------------聚合函數-------------------------------------------- 312 313 select max(sId) from student 314 select min(sId)from student 315 select avg(math) from score-----不會計算值為null 的列 316 select sum(math) from score 317 select count(*) from score 318 select sum(math)/count(*) from score 319 320 select max(sBirthday),min(sBirthday) from student where sSex='男' 321 322 323 324 select * from Student 325 select * from Score 326 select * from Class 327 328 -----------------------------帶條件的查詢--------------------------------------------- 329 330 --Select …from…where 331 --查詢沒有及格的學生的學號 332 select studentId from score where english<60 333 --查詢年齡在20-30歲之間的男學生 334 select sName from student where sAge>=20 and sAge<=30 335 --Between…and …在之間 336 --查詢年齡在20-30歲之間的男學生 337 select sName from student where sAge between 20 and 30 338 --查詢班級id為1,2,3的所有學生 339 select sId,sName from student where sId=1 or sId=2 or sId=3 340 select sId,sName from student where sId in(1,2,3) 341 342 ---------------------------模糊查詢--------------------------------------------------------- 343 344 ----查詢所有姓張的同學 345 select * from student where left(sname,1)='張'---局限性太大 346 select * from student where sName like '張%'---%匹配零個或多個任意字符 347 select * from student where sName like '張_'----- _匹配任意的一個字符 348 select * from student where sName like '_[兩]%'----- []匹配[]內的一個字符 349 select * from student where sName like '_[飛兩]%'----- []匹配[]內的一個字符 350 351 352 ---------------------------------------NULL值處理--------------------------------------------- 353 354 -----null表示“不知道”,而不是表示沒有 355 select null+1 ---結果是null,因為“不知道”加1的結果還是“不知道”。 356 357 select * from score where math =null---錯誤寫法 358 select * from score where math is null 359 select * from score where math is not null 360 361 ---------------------------------------order by asc ,desc 數值排序,默認升序asc--------------------------------------- 362 363 --按照年齡升序排序所有學生信息的列表 364 select * from student order by sAge asc 365 --按照英語成績從大到小排序,如果英語成績相同則按照數學成績從大到小排序 366 select * from score order by english desc,math desc 367 --ORDER BY子句要放到WHERE子句之后 368 select * from score 369 where english>80 370 order by english desc,math desc 371 372 ---------------------------------------group by 數據分組------------------------------------------ 373 374 --按照班級進行分組統計各個班級的人數 375 select cName,count(*)from class 376 group by cName 377 378 --GROUP BY子句必須放到WHERE語句的之后 379 select sSex,count(*) from student 380 where sAge>18 381 group by sSex 382 383 --聚合函數不能出現在where子句中 384 select sSex,count(*) from student 385 where sAge>18 and avg(sAge)>19 386 group by sSex 387 388 389 --沒有出現在GROUP BY子句中的列是不能放到SELECT語句后的列名列表中的 (聚合函數中除外) 390 391 --select sSex,count(*), avg(sAge),sName from student --錯誤,sName不能放select在列表中 392 select sSex,count(*), avg(sAge) from student 393 where sAge>18 394 group by sSex 395 396 ----------------------------having 對分組后的內容進行條件選擇------------------------------------------- 397 398 --在Where中不能使用聚合函數,Having中可以,Having要位於Group By之后,而且having中的列要在select中存在 399 --錯誤,sAge列在select中不存在,而且它也不是聚合函數 400 --select sSex,count(*), avg(sAge) from student 401 --group by sSex 402 --having sAge>18 and avg(sAge)>19 403 404 select sSex,count(*), avg(sAge) from student 405 group by sSex 406 having avg(sAge)>19 407 408 409 410 --------練習------------- 411 --求男生和女生分別有多少人 412 select sSex,count(*) from student 413 group by sSex 414 415 --每個班中的男同學的平均年齡 416 --select * from student 417 select count(*) , avg(sAge),sClassId from student 418 where sSex='男' 419 group by sClassId 420 --求平均年齡小於22的那些班 421 select sClassId from student 422 group by sClassId 423 having avg(sAge)<22 424 425 -----------------------------------------union 聯合結果集--------------------------------------------- 426 427 --列的個數一致,類型一致(兼容) 428 --排序 去除重復數據 429 select * from student 430 select * from teacher 431 select sId ,sSex,sName from student union select tId,tSex ,tName from teacher 432 433 --union all 434 --直接連接兩個結果集,不排序,不去除重復,效率高 435 select sId ,sSex,sName from student union all select tId,tSex ,tName from teacher 436 437 --要求在一個表格中查詢出學生的英語最高成績、最低成績、平均成績 438 select max(english),min(english),avg(english) from score 439 select '最高成績',max(english)from score union all select '最低成績',min(english)from score union all select'平均成績', avg(english) from score 440 --查詢每位老師的信息,包括姓名、工資,並且在最后一行加上平均工資和最高工資 441 --alter table teacher 442 --add tSalary int 443 select tName,tSalary from teacher 444 union all select '平均工資',avg(tSalary) from teacher 445 union all select '總工資',sum(tSalary) from teacher 446 447 -------------------------------一次插入多條數據---------------------------------------------- 448 insert into score 449 select 1,66,88 union 450 select 2,85,78 union 451 select 3,36,98 452 453 --把現有表的數據插入到新表(表不能存在) 454 select * into newStudent from student 455 select * from newStudent 456 truncate table newStudent 457 --把現有表的數據復制到一個已存在的表 458 ---要先把設置的自動增長列干掉 459 insert into newStudent select sName, sSex, sAge, sBirthday, sClassId, sNo from student 460 461 462 ----------------------------------------------------數據檢索結束--------------------------------------------------------------- 463 464 465 ------------------------------------------------------------sql中的函數---------------------------------------------------------- 466 467 -------------------------------------字符串處理函數---------------------------------------------------------- 468 select len(3455) 469 select len(getdate()) 470 --LOWER() 、UPPER () :轉小寫、大寫 471 select lower('ADGBAddf') 472 select upper('ADGBAddf') 473 --LTRIM():字符串左側的空格去掉 474 select ltrim(' adga ') 475 --RTRIM () :字符串右側的空格去掉 476 select rtrim(' adga ')+'123' 477 --去除左右空格方法 478 --LTRIM(RTRIM(' bb ')) 479 select '456'+ltrim(rtrim(' dag ')+'12') 480 --LEFT()、RIGHT() 截取取字符串 481 select left('2344',1) 482 select right('2344',1) 483 --SUBSTRING(string,start_position,length) 484 select substring('23444',1,2)---注意起始位置從一開始,和c#不同 485 486 487 ----------------------------------------------------日期函數-------------------------------------------------------- 488 489 --GETDATE() :取得當前日期時間 490 select getdate() 491 --DATEADD (datepart , number, date ),計算增加以后的日期。參數date為待計算的日期;參數number為增量;參數datepart為計量單位,可選值見幫助 492 select dateadd(day,1,getdate()) 493 select dateadd(year,1,getdate()) 494 select dateadd(month,1,getdate()) 495 select dateadd(hour,1,getdate()) 496 497 --獲取年月日 498 select year(getdate()) 499 select month(getdate()) 500 select day(getdate()) 501 --DATEDIFF ( datepart , startdate , enddate ) :計算兩個日期之間的差額。 datepart 為計量單位,可取值參考DateAdd。 502 select datediff(day,'2013-06-10',getdate()) 503 504 --DATEPART (datepart,date):返回一個日期的特定部分 505 select datepart(year,getdate()) 506 --datename datepart 507 select datename(year,getdate()) --字符串 508 select datepart(year,getdate()) --整數 509 510 ----------------------------------------------類型轉換函數-------------------------------------- 511 --問題 512 --select '平均分數' + 123 513 --select avg(english) from score 514 --select * from student 515 516 --CAST ( expression AS data_type) 517 select '平均分數' + cast(123 as varchar(10))--解決了字符串和整數連接的問題 518 select cast(34.89 as int)--沒有進位 519 select cast (round(89.6,0) as int) --有進位 520 select cast(78.98534 as decimal(10,2))--有進位,decimal的第一個參數是最大有效位,第二個參數是小數位數 521 select cast(avg(english) as decimal(4,2)) from score---解決了小數點位數過長的問題, 522 --CONVERT ( data_type, expression) 523 select convert(int,56.87)--沒有進位 524 select convert(decimal(4,2),56.86)--有進位 525 526 select convert(varchar(30),getdate(),20)--2013-06-15 14:01:39 527 select convert(varchar(20),getdate(),21) 528 select convert(varchar(30),getdate(),23)--國內標准年月日2013-06-15 529 select convert(varchar(10),getdate(),108)--國內標准時分秒14:00:32 530 531 select convert(varchar(10),getdate(),20)--通過截取字符串獲得國內標准年月日 532 533 ----------------------空值處理函數------------------------------------ 534 --ISNULL(expression,value) :如果expression不為空則返回expression,否則返回value。 535 --select * from score 536 select studentId,isnull(math,0) from score 537 538 select avg(english) from score 539 select sum(english)/count(sId) from score 540 select cast(avg(isnull(english,0)) as decimal(10,2)) from score------對於計算平均值很有用 541 542 543 ------------------------------------------------練習----------------------------------------------------- 544 545 ---------------練習1 未完成------------------------------------------------------------- 546 創建 MyCompany數據庫 547 548 部門表 department 549 dId 550 dName 551 員工表 employee 552 eId 553 eName 554 eSex 555 eAge 556 eSalary 557 eDepId 558 559 建庫 建表 建約束 添加測試數據 更新 和刪除 560 561 562 563 1、查詢所有員工 564 2、查詢工資超過2000快錢的員工 565 3、查詢最新進來的5個員工 566 4、查詢員工的平均工資,平均工資 567 5、查詢總共有多少員工 568 6、查詢每個部門有多少員工 569 7、查詢每個部門的平均工資 570 8、查詢每個部門男員工的平均工資 571 9、查詢平均工資超過2000的那些部門 572 10、查詢員工工資(姓名,工資)的同時,同一結果集顯示平均工資和最高工資 573 11、查詢名字里包含'定,月'的這些員工,並對結果按照年齡排序 574 575 -------------------------------練習1結束--------------------------------------------------------------------------- 576 577 ---------------練習2未完成------------------------------------------------------------- 578 579 --創建一張表,記錄電話呼叫員的工作流水,記錄呼叫員編號、對方號碼、通話開始時間、通話結束時間。 580 --建表、插數據等最后都自己寫SQL語句。 581 --drop table CallRecords 582 --use MySchool 583 --go 584 --create table CallRecords 585 --( 586 -- cId int identity(1,1) primary key, 587 -- cNo int not null, 588 -- cCllNumber varchar(6), 589 -- cStartTime datetime, 590 -- cEndTime datetime 591 --) 592 use MySchool 593 go 594 CREATE TABLE [CallRecords] 595 ( 596 [Id] [int] NOT NULL identity(1,1), 597 [CallerNumber] [nvarchar](50), --三位數字 598 [TelNum] [varchar](50), 599 [StartDateTime] [datetime] NULL, 600 [EndDateTime] [datetime] NULL --結束時間要大於開始時間,默認當前時間 601 ) 602 603 --主鍵約束 604 alter table [CallRecords] 605 add constraint PK_CallRecords primary key(id) 606 607 --檢查約束 608 alter table [CallRecords] 609 add constraint CK_CallRecords check(CallerNumber like '[0-9][0-9][0-9]') 610 611 alter table [CallRecords] 612 add constraint CK_CallRecords_EndDateTime check(EndDateTime > StartDateTime) 613 614 --默認約束 615 alter table [CallRecords] 616 add constraint DF_CallRecords default(getdate()) for EndDateTime 617 618 619 620 INSERT [dbo].[CallRecords] ([CallerNumber], [TelNum], [StartDateTime], [EndDateTime]) VALUES ('001', '0208888888', CAST(0x00009DAF00A4CB80 AS DateTime), CAST(0x00009DAF00A62E94 AS DateTime)); 621 INSERT [dbo].[CallRecords] ([CallerNumber], [TelNum], [StartDateTime], [EndDateTime]) VALUES ('001', '0208888888', CAST(0x00009DB000D63BC0 AS DateTime), CAST(0x00009DB000D68DC8 AS DateTime)); 622 INSERT [dbo].[CallRecords] ([CallerNumber], [TelNum], [StartDateTime], [EndDateTime]) VALUES ('001', '89898989', CAST(0x00009DB000E85C60 AS DateTime), CAST(0x00009DB000E92F50 AS DateTime)); 623 INSERT [dbo].[CallRecords] ([CallerNumber], [TelNum], [StartDateTime], [EndDateTime]) VALUES ('002', '98987676', CAST(0x00009DB2015BB7A0 AS DateTime), CAST(0x00009DB2015C4DA0 AS DateTime)); 624 INSERT [dbo].[CallRecords] ([CallerNumber], [TelNum], [StartDateTime], [EndDateTime]) VALUES ('002', '02188839389', CAST(0x00009DA4014C9C70 AS DateTime), CAST(0x00009DA4014E0308 AS DateTime)); 625 INSERT [dbo].[CallRecords] ([CallerNumber], [TelNum], [StartDateTime], [EndDateTime]) VALUES ('001', '767676766', CAST(0x00009DB400DAA0C0 AS DateTime), CAST(0x00009DB400DD5FE0 AS DateTime)); 626 INSERT [dbo].[CallRecords] ([CallerNumber], [TelNum], [StartDateTime], [EndDateTime]) VALUES ('003', '0227864656', CAST(0x00009DB200B9AB40 AS DateTime), CAST(0x00009DB200B9FC1C AS DateTime)); 627 INSERT [dbo].[CallRecords] ([CallerNumber], [TelNum], [StartDateTime], [EndDateTime]) VALUES ('003', '676765777', CAST(0x00009DB8014042B8 AS DateTime), CAST(0x00009DB80141804C AS DateTime)); 628 INSERT [dbo].[CallRecords] ([CallerNumber], [TelNum], [StartDateTime], [EndDateTime]) VALUES ('001', '89977653', CAST(0x00009D9A00FB9898 AS DateTime), CAST(0x00009D9A00FE6118 AS DateTime)); 629 INSERT [dbo].[CallRecords] ([CallerNumber], [TelNum], [StartDateTime], [EndDateTime]) VALUES ('004', '400400400', CAST(0x00009D9A00FB9898 AS DateTime), CAST(0x00009D9A00FE6118 AS DateTime)); 630 631 632 --要求: 633 --輸出所有數據中通話時間最長的5條記錄。orderby datediff 634 select top 5 datediff(second,[StartDateTime],[EndDateTime]), Id, CallerNumber, TelNum, StartDateTime, EndDateTime from CallRecords 635 order by datediff(second,[StartDateTime],[EndDateTime])desc 636 --輸出所有數據中撥打長途號碼(對方號碼以0開頭)的總時長。like、sum 637 --輸出本月通話總時長最多的前三個呼叫員的編號。 638 -- 639 --輸出本月撥打電話次數最多的前三個呼叫員的編號.group by,count(*) 640 641 642 643 ---------------練習2結束------------------------------------------------------------ 644 645 646 647 ----------------------------------------------sql基本命令結束--------------------------------------------------------------------- 648 649 650 651 652 653 654 655 656 ----------------------------------------------sql高級命令開始------------------------------------------------------------ 657 658 ----創建示例數據庫demo 659 create database demo 660 use demo 661 go 662 create table [user] 663 ( 664 [uId] int identity(1,1) primary key, 665 [name] varchar(50), 666 [level] int --1骨灰2大蝦3菜鳥 667 ) 668 insert into [user] (name,level) values('犀利哥',1) 669 insert into [user] (name,level) values('小月月',2) 670 insert into [user] (name,level) values('芙蓉姐姐',3) 671 672 673 ----------case end 相當於switch case 674 675 -----------then后面的返回值類型必須一致 676 677 --case end第一種用法,注意 字段level在case 后,when后面跟的是一個常量 678 select name, 679 case level 680 when 1 then '菜鳥' 681 when 2 then '骨灰' 682 else '大神' 683 end as '級別' 684 from [user] 685 686 use myschool 687 go 688 select * from score 689 --case end第二種用法,相當於多重if語句,注意case后面沒有字段,when后面為一個表達式 690 select studentid, 691 case 692 when english>=90 then '優秀' 693 when english>=80 then '良好' 694 when english>=60 then '及格' 695 else '不及格' 696 end as '成績等級' 697 from score 698 699 ----------練習1--------表中有A B C三列,用SQL語句實現:當A列大於B列時選擇A列否則選擇B列,當B列大於C列時選擇B列否則選擇C列。 700 select 701 case 702 when A>B then A 703 else B 704 end as 'AB列中的大值', 705 case 706 when B>C then B 707 else C 708 end as 'BC列中的大值' 709 from t 710 711 --------練習2------ 712 713 -- 單號 金額 714 -- Rk1 10 715 -- Rk2 20 716 -- Rk3 -30 717 -- Rk4 -10 718 -- 將上面的表輸出為如下的格式: 719 -- 單號 收入 支出 720 -- Rk1 10 0 721 -- Rk2 20 0 722 -- Rk3 0 30 723 -- Rk4 0 10 724 use demo 725 go 726 --成績示例表 727 create table test 728 ( 729 number varchar(10), 730 amount int 731 ) 732 insert into test(number,amount) values('RK1',10) 733 insert into test(number,amount) values('RK2',20) 734 insert into test(number,amount) values('RK3',-30) 735 insert into test(number,amount) values('RK4',-10) 736 737 select * from test 738 739 select number, 740 case 741 when amount>0 then amount 742 else 0 743 end as '收人', 744 case 745 when amount >0 then 0 746 else (0-amount) 747 end as '支出' 748 from test 749 750 751 -----------練習3---------- 752 753 -- 有一張表student0,記錄學生成績 754 -- name subject result 755 -- 張三 語文 80 756 -- 張三 數學 90 757 -- 張三 物理 85 758 -- 李四 語文 85 759 -- 李四 數學 92 760 -- 李四 物理 NULL 761 762 -- 要求輸出下面的格式: 763 -- name 語文 數學 物理 764 -- ---------- ----------- ----------- ----------- 765 -- 李四 85 92 0 766 -- 張三 80 90 85 767 768 use demo 769 ---示例表 770 CREATE TABLE student0 (name nvarchar(10),subject nvarchar(10),result int) 771 INSERT INTO student0 VALUES ('張三','語文',80) 772 INSERT INTO student0 VALUES ('張三','數學',90) 773 INSERT INTO student0 VALUES ('張三','物理',85) 774 INSERT INTO student0 VALUES ('李四','語文',85) 775 INSERT INTO student0 VALUES ('李四','數學',92) 776 INSERT INTO student0 VALUES ('李四','物理',null) 777 778 select [name], 779 isnull(sum(case 780 when subject='語文' then result 781 end ),0)as '語文', 782 isnull(sum(case 783 when subject='數學' then result 784 end),0) as '數學', 785 isnull(sum(case 786 when subject='物理' then result 787 end ),0)as '物理' 788 from student0 789 group by [name] 790 791 792 -------------------------------------------------子查詢---------------------------------------------------------- 793 794 795 --將一個查詢語句做為一個結果集供其他SQL語句使用,就像使用普通的表一樣,被當作結果集的查詢語句被稱為子查詢 796 797 select * from student 798 select * from(select * from student where sage>20)as t 799 800 --要求在一個表格中查詢出學生的英語最高成績、最低成績、平均成績 801 select(select max(english) from score) as maxenglish,(select min(english) from score) as minenglish,(select avg(english) from score) as avgenglish 802 --只有返回且僅返回一行、一列數據的子查詢才能當成單值子查詢 803 --select(select * from score)--錯誤 804 --查詢高二二班的所有學生 805 select * from student where sClassId in(select cId from class where cName='高二二班') 806 807 --查詢高一一班和高二一班的所有學生 808 809 select * from student where sClassId in(select cId from class where cName='高二二班' or cName='高二一班') 810 811 --查詢劉關張的成績 812 select * from score where studentid in(select sid from student where sname='關羽' or sname='劉備' or sname='張飛') 813 814 --快速實現刪除多個學生 815 delete from student where where sname='關羽' or sname='劉備' or sname='張飛' 816 817 --數據庫中分頁的實現 818 819 --取最近插入的1-3個學生 820 select top 3 * from student 821 where sid not in 822 (select top 0 sid from student order by sid desc) 823 order by sid desc 824 --取最近插入的第4-6個學生 825 select top 3 * from student 826 where sid not in 827 (select top 3 sid from student order by sid desc) 828 order by sid desc 829 830 --取最近插入的第7-9個學生 831 select top 3 * from student 832 where sid not in 833 (select top 6 sid from student order by sid desc) 834 order by sid desc 835 836 --取最近插入的第(3n-2)-3n個學生 837 select top 3 * from student 838 where sid not in 839 (select top 3(n-1) sid from student order by sid desc) 840 order by sid desc 841 842 ----------------------row_number()------sql 2005中的分頁--------------------------------------------- 843 844 845 ----row_number()over (order by sid) as num 846 select * from (select row_number()over (order by sid) as num,* from student )as t 847 where num between 1 and 3 848 849 select * from (select row_number()over (order by sid) as num,* from student )as t 850 where num between 4and 6 851 852 select * from (select row_number()over (order by sid) as num,* from student )as t 853 where num between 7 and 9 854 855 select * from (select row_number()over (order by sid) as num,* from student )as t 856 where num between (3n-2) and 3n 857 858 -------------------------表連接------------------------------------------------ 859 --交叉連接,全連接 860 select * from student 861 cross join class 862 863 --左外連接 864 select * from student 865 left join class on sclassid=cid 866 867 --右外連接 868 select * from student 869 right join class on sclassid=cid 870 871 ---內連接,等值連接 872 select * from student 873 inner join class on sclassid=cid 874 875 --同上效果的寫法,也是經常的寫法 876 select * from student,class 877 where sclassid=cid 878 879 --查詢所有學生的姓名、年齡及所在班級 880 select sname ,sage,cname from student 881 inner join class on sclassid=cid 882 883 --查詢年齡超過20歲的學生的姓名、年齡及所在班級 884 select sname,sage,cname from student,class 885 where sclassid=cid and sage>20 886 887 --查詢學生姓名、年齡、班級及成績 888 select sname,sage,cname,english from student 889 inner join class on sclassid=cid 890 inner join score on student.sid=studentid 891 892 --查詢所有學生(參加及未參加考試的都算)及成績 893 894 select * from student 895 left join score on student.sid=studentid 896 897 --查詢所有及格的學生姓名、年齡及成績 898 select sname,sage,english from student 899 inner join score on student.sid=studentid 900 where english>60 901 902 --查詢所有參加考試的(分數不為null)學生姓名、年齡及成績,班級 903 904 select sname,sage,english,cname from student 905 inner join class on sclassid=cid 906 inner join score on student.sid=studentid 907 where english is not null 908 909 --查詢所有學生(參加和未參加考試)的學生姓名、年齡、成績,如果沒有參加考試顯示缺考,如果小於60分顯示不及格 910 911 select sname,sage, 912 case 913 when english>=60 then cast( english as nvarchar(10)) 914 when english<60 then '不及格' 915 when english is null then '缺考' 916 end 917 from student 918 inner join score on student.sid=studentid 919 920 -----------------------------------視圖-------------------------------------------------------- 921 -----系統視圖 922 select * from sys.tables 923 select * from sys.objects 924 ----系統表 925 select * from sysobjects 926 927 928 --利用系統視圖去做一些操作 929 if exists(select * from sys.databases where name='demo') 930 drop database demo 931 create database demo 932 go 933 use demo 934 go 935 if exists(select * from sys.objects where name='test') 936 drop table test 937 create table test 938 ( 939 tId int identity(1,1) primary key, 940 tName nvarchar(10) 941 ) 942 943 if exists(select * from sys.objects where name='UQ_test_tName') 944 alter table test drop constraint UQ_test_tName 945 alter table test 946 add constraint UQ_test_tName unique(tName) 947 948 949 -------創建視圖 950 use MySchool 951 if exists(select * from sys.objects where name='v_Student') 952 drop view v_Student 953 go 954 create view v_Student 955 as 956 select sName,sAge,sSex from student 957 958 959 960 select * from v_Student 961 962 963 if exists(select * from sys.objects where name='v_Student1') 964 drop view v_Student1 965 go 966 create view v_Student1 967 as 968 select sName,sAge, 969 case 970 when english is null then '缺考' 971 when english < 60 then '不及格' 972 else convert(varchar,english) 973 end as '成績' 974 from student 975 left join score on student.sId = studentId 976 977 978 979 select * from v_Student1 980 981 982 select * from view_2 where name='劉備' 983 984 985 -------sql中的局部變量 986 987 declare @ssex nvarchar(10),@sname nvarchar(10) 988 --set @ssex='男' ---只能為一個變量賦值 989 --select @sname='劉備',@ssex='男' ---可為多個變量賦值 990 select @sname=sname from student where sid=1 ----可以把sql查詢的結果賦給變量 991 992 select @sname,@ssex 993 994 print @sname -----只能輸出一個值 995 996 --全局變量 997 998 ---全局變量是系統定義的,只讀的 999 1000 select @@version 1001 1002 select @@error 1003 1004 select @@identity 1005 1006 select @@LANGUAGE 1007 1008 select @@servername 1009 1010 select @@rowcount 1011 1012 1013 ------------------if--else 條件判斷--------------------- 1014 1015 --計算平均分數並輸出,如果平均分數超過60分輸出成績最高的三個學生的成績,否則輸出后三名的學生 1016 1017 declare @avg float 1018 select @avg=avg(english) from score 1019 if(@avg>=60) 1020 begin 1021 select top 3 * from score order by sid desc 1022 end 1023 else 1024 begin 1025 select top 3 * from score order by sid asc 1026 end 1027 1028 1029 --------------while----------- 1030 1031 --如果不及格的人超過半數(考試題出難了),則給每個人增加2分 1032 declare @count int,@failcount int 1033 select @count=count(*) from score 1034 select @failcount=count(*) from score where english<60 1035 1036 while(@failcount>@count/2) 1037 begin 1038 update score set english=english+2 1039 select @failcount=count(*) from score where english<60 1040 end 1041 update score set english=100 where english>100 1042 1043 select * from score 1044 1045 1046 --把所有未及格的人的成績都加及格 1047 declare @count int,@i int 1048 select @count=count(*) from score where english < 60 1049 set @i = 0 1050 while(@count > 0) 1051 begin 1052 set @i = @i + 1 1053 update score set english = english + 2 1054 select @count=count(*) from score where english < 60 1055 end 1056 update score set english = 100 where english > 100 1057 select * from score 1058 select @i 1059 1060 1061 ------------------------------事務-------------------------------------------- 1062 1063 --轉賬問題: 1064 -- 假定錢從A轉到B,至少需要兩步: 1065 -- A的資金減少 1066 -- 然后B的資金相應增加 1067 1068 ------示例表 1069 use demo 1070 go 1071 create table bank 1072 ( 1073 cId char(4) primary key, 1074 balance money, --余額 1075 ) 1076 1077 alter table bank 1078 add constraint CH_balance check(balance >=10) 1079 1080 go 1081 --delete from bank 1082 insert into bank values('0001',1000) 1083 insert into bank values('0002',10) 1084 1085 update bank set balance=balance-1000 where cid='0001' 1086 update bank set balance=balance + 1000 where cid='0002' 1087 --查看結果。 1088 SELECT * FROM bank 1089 1090 1091 ----指訪問並可能更新數據庫中各種數據項的一個程序執行單元(unit)--也就是由多個sql語句組成,必須作為一個整體執行 1092 --這些sql語句作為一個整體一起向系統提交,要么都執行、要么都不執行 1093 1094 1095 --事務 1096 declare @sumError int 1097 set @sumError = 0 1098 begin tran --transaction 1099 update bank set balance = balance + 1000 where cId = '0002' 1100 set @sumError = @sumError + @@error 1101 update bank set balance = balance - 1000 where cid='0001' 1102 set @sumError = @sumError + @@error 1103 --事務執行成功 提交事務 1104 if(@sumError = 0) 1105 commit tran 1106 --事務執行失敗,回滾 1107 else 1108 rollback tran 1109 1110 select @sumError 1111 1112 1113 --查看結果。 1114 SELECT * FROM bank 1115 1116 1117 1118 ----------------存儲過程---------------------------------- 1119 1120 --存儲過程---就像數據庫中運行方法(函數) 1121 1122 --系統存儲過程 1123 1124 EXEC sp_databases 1125 EXEC sp_renamedb 'Northwind','Northwind1' 1126 EXEC sp_tables 1127 EXEC sp_columns stuInfo 1128 EXEC sp_help stuInfo 1129 EXEC sp_helpconstraint stuInfo 1130 EXEC sp_helpindex stuMarks 1131 EXEC sp_helptext 'view_stuInfo_stuMarks' 1132 EXEC sp_stored_procedures 1133 1134 ---分離數據庫 1135 exec sp_detach_db test 1136 --附加數據庫 1137 exec sp_attach_db @dbname='test',@filename1='C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Data\test.mdf',@filename2='C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Data\test_log.LDF' 1138 1139 1140 -----創建存儲過程 1141 1142 -----逐步提分,使及格人數大於一半 1143 1144 if exists(select * from sys.objects where name='usp_upGrade') 1145 drop procedure usp_upGrade 1146 1147 go 1148 1149 create proc usp_upGrade 1150 --這里可以放置輸入輸出型參數 1151 as 1152 declare @count int,@failcount int 1153 select @count=count(*) from score 1154 select @failcount=count(*) from score where english<60 1155 while(@failcount>@count/2) 1156 begin 1157 update score set english=english+2 1158 select @failcount=count(*) from score where english<60 1159 end 1160 update score set english=100 where english>100 1161 1162 ---執行存儲過程 1163 execute usp_upGrade 1164 1165 1166 use MySchool 1167 go 1168 select * from score 1169 1170 --帶參數的存儲過程 1171 --帶默認值參數 1172 1173 -------找出英語成績不及格的人數 1174 1175 if exists(select * from sys.objects where name='usp_GetFailEnglishNum') 1176 drop procedure usp_GetFailEnglishNum 1177 1178 go 1179 1180 create proc usp_GetFailEnglishNum 1181 @failEnglish float=60 ----帶默認值的 輸入型參數 1182 as 1183 declare @failcount int 1184 select @failcount=count(*) from score where english<@failEnglish 1185 print @failcount 1186 1187 --執行存儲過程 1188 execute usp_GetFailEnglishNum----使用默認值 1189 1190 execute usp_GetFailEnglishNum 50----自己賦值 1191 execute usp_GetFailEnglishNum @failEnglish=50----另一種賦值方法 1192 1193 select * from score 1194 1195 1196 -----存儲過程輸出值 return 1197 if exists(select * from sys.objects where name='usp_GetFailEnglishNum') 1198 drop procedure usp_GetFailEnglishNum 1199 1200 go 1201 1202 create proc usp_GetFailEnglishNum 1203 @failEnglish float=60 ----帶默認值的 輸入型參數 1204 as 1205 declare @failcount int,@count int 1206 select @failcount=count(*) from score where english<@failEnglish 1207 print @failcount 1208 select @count=count(*) from score 1209 return @count 1210 1211 --調用有返回值的存儲過程 1212 declare @count int 1213 execute @count=usp_GetFailEnglishNum 1214 print @count 1215 1216 1217 ------帶輸出參數的存儲過程的創建 1218 1219 if exists(select * from sys.objects where name='usp_GetFailEnglishNum') 1220 drop procedure usp_GetFailEnglishNum 1221 1222 go 1223 1224 create proc usp_GetFailEnglishNum 1225 @failEnglish float=60,----帶默認值的 輸入型參數 1226 @countNum int output -----輸出型參數 1227 as 1228 declare @failcount int,@count int 1229 select @failcount=count(*) from score where english<@failEnglish 1230 print @failcount 1231 select @count=count(*) from score 1232 set @countNum= @count --給輸出型參數賦值 1233 1234 --調用有返回值的存儲過程 1235 declare @count int 1236 execute usp_GetFailEnglishNum 60, @count output 1237 print @count 1238 1239 ------------------分頁存儲過程--------------------- 1240 1241 ---要輸入要顯示的頁碼和每頁顯示的條數。輸出總共的頁碼數 1242 use MySchool 1243 go 1244 if exists(select * from sys.objects where name='usp_GetPageData') 1245 drop procedure usp_GetPageData 1246 go 1247 1248 create proc usp_GetPageData 1249 1250 @pageCount int output,----輸出型參數 總共的頁碼數目 1251 @pageIndex int =1 , ---輸入型參數,當前要顯示的頁碼 1252 @pageSize int =20 ----輸入型參數,每頁顯示的記錄數目 1253 1254 as 1255 declare @count int -----設置變量用於接收總的記錄數, 1256 select * from(select row_number() over(order by sid) as num ,* from student) as t 1257 where num between @pageSize*@pageIndex-@pageSize+1 and @pageSize*@pageIndex 1258 order by sid desc 1259 select @count=count(*) from student 1260 1261 ---求總共有多少頁 1262 set @pageCount=ceiling((@count/convert(float,@pageSize))) --select ceiling(7/3.0) 1263 1264 --執行存儲過程 1265 1266 declare @pageCount int 1267 execute usp_GetPageData @pageCount output,2,3 1268 select @pageCount as '總頁碼數目' 1269 1270 select * from student 1271 1272 1273 1274 --------------實現登陸的存儲過程---------不是自己寫的---------------- 1275 1276 if exists(select * from sys.objects where name='usp_Login') 1277 drop proc usp_Login 1278 go 1279 create proc usp_Login 1280 @name varchar(10), 1281 @pwd varchar(10), 1282 @isLogin int output --1 登陸成功 2用戶名錯誤 3密碼錯誤 4密碼錯誤超過3次 1283 as 1284 declare @times int --錯誤次數 1285 --根據用戶名是否存在 1286 if exists(select * from [user] where uUserName=@name) 1287 begin 1288 select @times = uTimes from [user] where uUserName=@name 1289 if(@times = 3) 1290 --密碼錯誤3次 1291 set @isLogin=4 1292 else 1293 begin 1294 if exists(select * from [user] where uUserName=@name and uPwd=@pwd) 1295 begin 1296 --用戶名密碼正確 登陸成功 1297 set @isLogin=1 1298 update [user] set uTimes=0 where uUserName=@name 1299 end 1300 else 1301 begin 1302 --密碼錯誤 1303 set @isLogin=3 1304 update [user] set uTimes=uTimes + 1 where uUserName=@name 1305 end 1306 end 1307 end 1308 else 1309 --用戶名不存在 1310 set @isLogin= 2 1311 1312 1313 1314 1315 -----------------------------觸發器------------------------------------------------------ 1316 1317 1318 --觸發器是一種特殊類型的存儲過程 1319 --一般的存儲過程通過存儲過程名稱被直接調用,而觸發器主要是通過事件進行觸發而被執行 1320 --常見的觸發器有三種:分別應用於Insert , Update , Delete 事件 1321 1322 use MySchool 1323 go 1324 if exists(select * from sys.objects where name='tr_insertStudent') 1325 drop trigger tr_insertStudent 1326 go 1327 1328 create trigger tr_insertStudent 1329 1330 on score for insert 1331 1332 as 1333 begin 1334 declare @stuId int,@sid int 1335 select @sid=sid,@stuId=studentId from inserted ---從插入的臨時表中獲取數據 1336 if not exists(select * from student where sid=@stuId) 1337 delete from score where sid=@sid 1338 else 1339 print '插入成功' 1340 end 1341 1342 select * from student 1343 select * from score 1344 insert into score values(9,33,66)