赞
踩
--将以下语句拷贝到SQL manager,分部执行 --创建数据库 create database schoolDB go use schoolDB go --创建学生表 create TABLE TStudent ( StudentID varchar(10) NOT NULL, Sname varchar(10) DEFAULT NULL, sex char(2) DEFAULT NULL, cardID varchar(20) DEFAULT NULL, Birthday datetime DEFAULT NULL, Email varchar(40) DEFAULT NULL, Class varchar(20) DEFAULT NULL, enterTime datetime DEFAULT NULL ) go --创建课程表 create table TSubject ( subJectID nvarchar(4), subJectName nvarchar(30), BookName nvarchar(30), Publisher nvarchar(20) ) go --创建分数表 create table TScore ( StudentID nvarchar(10), subJectID nvarchar(4), mark decimal ) go --插入课程信息 insert into TSubject values ('0001','网络管理','奠基计算机网络','清华出版社'); insert into TSubject values ('0002','软件测试','功能测试','人邮出版社'); insert into TSubject values ('0003','软件开发','企业级开发','人邮出版社') go --创建函数该函数能够产生学生姓名 create function create_name(@s float) RETURNS varchar(10) begin DECLARE @LN VARCHAR(300); DECLARE @MN VARCHAR(200); DECLARE @FN VARCHAR(200); DECLARE @LN_N INT; DECLARE @MN_N INT; DECLARE @FN_N INT; SET @LN='李王张刘陈杨黄赵周吴徐孙朱马胡郭林何高梁郑罗宋谢唐韩曹许邓萧冯曾程蔡彭潘袁于董余苏叶吕魏蒋田杜丁沈姜范江傅钟卢汪戴崔任陆廖姚方金邱夏谭韦贾邹石熊孟秦阎薛侯雷白龙段郝孔邵史毛常万顾赖武康贺严尹钱施牛洪龚'; SET @MN='伟刚勇春菊毅俊峰强军平保东文辉力明永健世广志瑗琰韵融园艺咏卿聪澜纯毓悦昭冰爽琬茗羽希宁欣飘育滢馥新利筠柔竹霭凝晓欢霄枫芸菲寒伊亚宜可姬舒义兴良海山仁波宁贵福生龙元全国胜学祥亮政谦亨奇固之岚苑富顺信子杰涛昌成康星光天达安岩中茂进林有坚和彪博诚先敬震振壮会思群豪清飞彬娜静淑惠珠翠雅芝妍茜秋珊莎锦黛青倩婷姣婉娴瑾颖露瑶怡婵雁蓓纨仪荷丹蓉眉君琴蕊薇菁梦素伟刚勇毅俊峰强军平保东文辉力明永健世广志义兴良海山仁波宁贵福生龙元全国胜学祥才发武新利清飞彬富顺信子杰涛昌成康星光天达安岩中茂进林有坚和彪博诚先敬震振壮会思群豪心邦承乐绍功松善厚庆磊民友裕河哲江超浩亮政谦亨奇固之轮翰朗伯宏言若鸣朋斌梁栋维启克伦翔旭鹏泽晨辰士以建家致树炎德行时泰盛雄琛钧冠策腾楠榕风航弘'; SET @FN='伟刚勇毅俊云莲真环雪荣爱妹霞香月莺媛艳瑞凡佳嘉琼勤珍贞莉桂娣叶璧才发武丽琳轮翰朗伯宏言若鸣朋斌梁栋维启克伦翔旭鹏泽晨辰士以建家致树炎德河哲江超浩璐娅琦晶裕华慧巧美婕馨影荔枝思心邦承乐绍功松善厚庆磊民友玉萍红娥玲芬芳燕彩兰凤洁梅秀娟英行时泰盛雄琛钧冠策腾楠榕风航弘峰强军平保东文辉力明永健世广志义兴良海山仁波宁贵福生龙元全国胜学祥才发武新利清飞彬富顺信子杰涛昌成康星光天达安岩中茂进林有坚和彪博诚先敬震振壮会思群豪心邦承乐绍功松善厚庆磊民友裕河哲江超浩亮政谦亨奇固之轮翰朗伯宏言若鸣朋斌梁栋维启克伦翔旭鹏泽晨辰士以建家致树炎德行时泰盛雄琛钧冠策腾楠榕风航弘'; SET @LN_N=len(@LN)*@s; SET @MN_N=len(@MN)*@s; SET @FN_N=len(@FN)*@s; return substring(@LN,@LN_N,1)+substring(@MN,@MN_N,1)+substring(@FN,@FN_N,1); end go --测试是否能产生新的姓名 select dbo.create_name(rand()) go --创建汉字转拼音的函数,用来产生用户的邮箱 create function dbo.fn_GetPinyin(@words nvarchar(2000)) returns varchar(8000) as begin declare @word nchar(1) declare @pinyin varchar(8000) declare @i int declare @words_len int declare @unicode int set @i = 1 set @words = ltrim(rtrim(@words)) set @words_len = len(@words) while (@i <= @words_len) --循环取字符 begin set @word = substring(@words, @i, 1) set @unicode = unicode(@word) set @pinyin = ISNULL(@pinyin +SPACE(0),'')+ (case when unicode(@word) between 19968 and 19968+20901 then (select top 1 py from ( select 'a' as py,N'厑' as word union all select 'ai',N'靉' union all select 'an',N'黯' union all select 'ang',N'醠' union all select 'ao',N'驁' union all select 'ba',N'欛' union all select 'bai',N'瓸' --韛兡瓸 union all select 'ban',N'瓣' union all select 'bang',N'鎊' union all select 'bao',N'鑤' union all select 'bei',N'鐾' union all select 'ben',N'輽' union all select 'beng',N'鏰' union all select 'bi',N'鼊' union all select 'bian',N'變' union all select 'biao',N'鰾' union all select 'bie',N'彆' union all select 'bin',N'鬢' union all select 'bing',N'靐' union all select 'bo',N'蔔' union all select 'bu',N'簿' union all select 'ca',N'囃' union all select 'cai',N'乲' --縩乲 union all select 'can',N'爘' union all select 'cang',N'賶' union all select 'cao',N'鼜' union all select 'ce',N'簎' union all select 'cen',N'笒' union all select 'ceng',N'乽' --硛硳岾猠乽 union all select 'cha',N'詫' union all select 'chai',N'囆' union all select 'chan',N'顫' union all select 'chang',N'韔' union all select 'chao',N'觘' union all select 'che',N'爡' union all select 'chen',N'讖' union all select 'cheng',N'秤' union all select 'chi',N'鷘' union all select 'chong',N'銃' union all select 'chou',N'殠' union all select 'chu',N'矗' union all select 'chuai',N'踹' union all select 'chuan',N'鶨' union all select 'chuang',N'愴' union all select 'chui',N'顀' union all select 'chun',N'蠢' union all select 'chuo',N'縒' union all select 'ci',N'嗭' --賜嗭 union all select 'cong',N'謥' union all select 'cou',N'輳' union all select 'cu',N'顣' union all select 'cuan',N'爨' union all select 'cui',N'臎' union all select 'cun',N'籿' union all select 'cuo',N'錯' union all select 'da',N'橽' union all select 'dai',N'靆' union all select 'dan',N'饏' union all select 'dang',N'闣' union all select 'dao',N'纛' union all select 'de',N'的' union all select 'den',N'扽' union all select 'deng',N'鐙' union all select 'di',N'螮' union all select 'dia',N'嗲' union all select 'dian',N'驔' union all select 'diao',N'鑃' union all select 'die',N'嚸' --眰嚸 union all select 'ding',N'顁' union all select 'diu',N'銩' union all select 'dong',N'霘' union all select 'dou',N'鬭' union all select 'du',N'蠹' union all select 'duan',N'叾' --籪叾 union all select 'dui',N'譵' union all select 'dun',N'踲' union all select 'duo',N'鵽' union all select 'e',N'鱷' union all select 'en',N'摁' union all select 'eng',N'鞥' union all select 'er',N'樲' union all select 'fa',N'髮' union all select 'fan',N'瀪' union all select 'fang',N'放' union all select 'fei',N'靅' union all select 'fen',N'鱝' union all select 'feng',N'覅' union all select 'fo',N'梻' union all select 'fou',N'鴀' union all select 'fu',N'猤' --鰒猤 union all select 'ga',N'魀' union all select 'gai',N'瓂' union all select 'gan',N'灨' union all select 'gang',N'戇' union all select 'gao',N'鋯' union all select 'ge',N'獦' union all select 'gei',N'給' union all select 'gen',N'搄' union all select 'geng',N'堩' --亙堩啹喼嗰 union all select 'gong',N'兣' --熕贑兝兣 union all select 'gou',N'購' union all select 'gu',N'顧' union all select 'gua',N'詿' union all select 'guai',N'恠' union all select 'guan',N'鱹' union all select 'guang',N'撗' union all select 'gui',N'鱥' union all select 'gun',N'謴' union all select 'guo',N'腂' union all select 'ha',N'哈' union all select 'hai',N'饚' union all select 'han',N'鶾' union all select 'hang',N'沆' union all select 'hao',N'兞' union all select 'he',N'靏' union all select 'hei',N'嬒' union all select 'hen',N'恨' union all select 'heng',N'堼' --堼囍 union all select 'hong',N'鬨' union all select 'hou',N'鱟' union all select 'hu',N'鸌' union all select 'hua',N'蘳' union all select 'huai',N'蘾' union all select 'huan',N'鰀' union all select 'huang',N'鎤' union all select 'hui',N'顪' union all select 'hun',N'諢' union all select 'huo',N'夻' union all select 'ji',N'驥' union all select 'jia',N'嗧' union all select 'jian',N'鑳' union all select 'jiang',N'謽' union all select 'jiao',N'釂' union all select 'jie',N'繲' union all select 'jin',N'齽' union all select 'jing',N'竸' union all select 'jiong',N'蘔' union all select 'jiu',N'欍' union all select 'ju',N'爠' union all select 'juan',N'羂' union all select 'jue',N'钁' union all select 'jun',N'攈' union all select 'ka',N'鉲' union all select 'kai',N'乫' --鎎乫 union all select 'kan',N'矙' union all select 'kang',N'閌' union all select 'kao',N'鯌' union all select 'ke',N'騍' union all select 'ken',N'褃' union all select 'keng',N'鏗' --巪乬唟厼怾 union all select 'kong',N'廤' union all select 'kou',N'鷇' union all select 'ku',N'嚳' union all select 'kua',N'骻' union all select 'kuai',N'鱠' union all select 'kuan',N'窾' union all select 'kuang',N'鑛' union all select 'kui',N'鑎' union all select 'kun',N'睏' union all select 'kuo',N'穒' union all select 'la',N'鞡' union all select 'lai',N'籟' union all select 'lan',N'糷' union all select 'lang',N'唥' union all select 'lao',N'軂' union all select 'le',N'餎' union all select 'lei',N'脷' --嘞脷 union all select 'leng',N'睖' union all select 'li',N'瓈' union all select 'lia',N'倆' union all select 'lian',N'纞' union all select 'liang',N'鍄' union all select 'liao',N'瞭' union all select 'lie',N'鱲' union all select 'lin',N'轥' --轥拎 union all select 'ling',N'炩' union all select 'liu',N'咯' --瓼甅囖咯 union all select 'long',N'贚' union all select 'lou',N'鏤' union all select 'lu',N'氇' union all select 'lv',N'鑢' union all select 'luan',N'亂' union all select 'lue',N'擽' union all select 'lun',N'論' union all select 'luo',N'鱳' union all select 'ma',N'嘛' union all select 'mai',N'霢' union all select 'man',N'蘰' union all select 'mang',N'蠎' union all select 'mao',N'唜' union all select 'me',N'癦' --癦呅 union all select 'mei',N'嚜' union all select 'men',N'們' union all select 'meng',N'霥' --霿踎 union all select 'mi',N'羃' union all select 'mian',N'麵' union all select 'miao',N'廟' union all select 'mie',N'鱴' --鱴瓱 union all select 'min',N'鰵' union all select 'ming',N'詺' union all select 'miu',N'謬' union all select 'mo',N'耱' --耱乮 union all select 'mou',N'麰' --麰蟱 union all select 'mu',N'旀' union all select 'na',N'魶' union all select 'nai',N'錼' union all select 'nan',N'婻' union all select 'nang',N'齉' union all select 'nao',N'臑' union all select 'ne',N'呢' union all select 'nei',N'焾' --嫩焾 union all select 'nen',N'嫩' union all select 'neng',N'能' --莻嗯鈪銰啱 union all select 'ni',N'嬺' union all select 'nian',N'艌' union all select 'niang',N'釀' union all select 'niao',N'脲' union all select 'nie',N'钀' union all select 'nin',N'拰' union all select 'ning',N'濘' union all select 'niu',N'靵' union all select 'nong',N'齈' union all select 'nou',N'譳' union all select 'nu',N'搙' union all select 'nv',N'衄' union all select 'nue',N'瘧' union all select 'nuan',N'燶' --硸黁燶郍 union all select 'nuo',N'桛' union all select 'o',N'鞰' --毮夞乯鞰 union all select 'ou',N'漚' union all select 'pa',N'袙' union all select 'pai',N'磗' --鎃磗 union all select 'pan',N'鑻' union all select 'pang',N'胖' union all select 'pao',N'礮' union all select 'pei',N'轡' union all select 'pen',N'喯' union all select 'peng',N'喸' --浌巼闏乶喸 union all select 'pi',N'鸊' union all select 'pian',N'騙' union all select 'piao',N'慓' union all select 'pie',N'嫳' union all select 'pin',N'聘' union all select 'ping',N'蘋' union all select 'po',N'魄' union all select 'pou',N'哛' --兺哛 union all select 'pu',N'曝' union all select 'qi',N'蟿' union all select 'qia',N'髂' union all select 'qian',N'縴' union all select 'qiang',N'瓩' --羻兛瓩 union all select 'qiao',N'躈' union all select 'qie',N'籡' union all select 'qin',N'藽' union all select 'qing',N'櫦' union all select 'qiong',N'瓗' union all select 'qiu',N'糗' union all select 'qu',N'覻' union all select 'quan',N'勸' union all select 'que',N'礭' union all select 'qun',N'囕' union all select 'ran',N'橪' union all select 'rang',N'讓' union all select 'rao',N'繞' union all select 're',N'熱' union all select 'ren',N'餁' union all select 'reng',N'陾' union all select 'ri',N'馹' union all select 'rong',N'穃' union all select 'rou',N'嶿' union all select 'ru',N'擩' union all select 'ruan',N'礝' union all select 'rui',N'壡' union all select 'run',N'橍' --橍挼 union all select 'ruo',N'鶸' union all select 'sa',N'栍' --櫒栍 union all select 'sai',N'虄' --簺虄 union all select 'san',N'閐' union all select 'sang',N'喪' union all select 'sao',N'髞' union all select 'se',N'飋' --裇聓 union all select 'sen',N'篸' union all select 'seng',N'縇' --閪縇 union all select 'sha',N'霎' union all select 'shai',N'曬' union all select 'shan',N'鱔' union all select 'shang',N'緔' union all select 'shao',N'潲' union all select 'she',N'欇' union all select 'shen',N'瘮' union all select 'sheng',N'賸' union all select 'shi',N'瓧' --鰘齛兙瓧 union all select 'shou',N'鏉' union all select 'shu',N'虪' union all select 'shua',N'誜' union all select 'shuai',N'卛' union all select 'shuan',N'腨' union all select 'shuang',N'灀' union all select 'shui',N'睡' union all select 'shun',N'鬊' union all select 'shuo',N'鑠' union all select 'si',N'乺' --瀃螦乺 union all select 'song',N'鎹' union all select 'sou',N'瘶' union all select 'su',N'鷫' union all select 'suan',N'算' union all select 'sui',N'鐩' union all select 'sun',N'潠' union all select 'suo',N'蜶' union all select 'ta',N'襨' --躢襨 union all select 'tai',N'燤' union all select 'tan',N'賧' union all select 'tang',N'燙' union all select 'tao',N'畓' --討畓 union all select 'te',N'蟘' union all select 'teng',N'朰' --霯唞朰 union all select 'ti',N'趯' union all select 'tian',N'舚' union all select 'tiao',N'糶' union all select 'tie',N'餮' union all select 'ting',N'乭' --濎乭 union all select 'tong',N'憅' union all select 'tou',N'透' union all select 'tu',N'鵵' union all select 'tuan',N'褖' union all select 'tui',N'駾' union all select 'tun',N'坉' union all select 'tuo',N'籜' union all select 'wa',N'韤' union all select 'wai',N'顡' union all select 'wan',N'贎' union all select 'wang',N'朢' union all select 'wei',N'躛' union all select 'wen',N'璺' union all select 'weng',N'齆' union all select 'wo',N'齷' union all select 'wu',N'鶩' union all select 'xi',N'衋' union all select 'xia',N'鏬' union all select 'xian',N'鼸' union all select 'xiang',N'鱌' union all select 'xiao',N'斆' union all select 'xie',N'躞' union all select 'xin',N'釁' union all select 'xing',N'臖' union all select 'xiong',N'敻' union all select 'xiu',N'齅' union all select 'xu',N'蓿' union all select 'xuan',N'贙' union all select 'xue',N'瀥' union all select 'xun',N'鑂' union all select 'ya',N'齾' union all select 'yan',N'灩' union all select 'yang',N'樣' union all select 'yao',N'鑰' union all select 'ye',N'岃' --鸈膶岃 union all select 'yi',N'齸' union all select 'yin',N'檼' union all select 'ying',N'譍' union all select 'yo',N'喲' union all select 'yong',N'醟' union all select 'you',N'鼬' union all select 'yu',N'爩' union all select 'yuan',N'願' union all select 'yue',N'鸙' union all select 'yun',N'韻' union all select 'za',N'雥' union all select 'zai',N'縡' union all select 'zan',N'饡' union all select 'zang',N'臟' union all select 'zao',N'竈' union all select 'ze',N'稄' union all select 'zei',N'鱡' union all select 'zen',N'囎' union all select 'zeng',N'贈' union all select 'zha',N'醡' union all select 'zhai',N'瘵' union all select 'zhan',N'驏' union all select 'zhang',N'瞕' union all select 'zhao',N'羄' union all select 'zhe',N'鷓' union all select 'zhen',N'黮' union all select 'zheng',N'證' union all select 'zhi',N'豒' union all select 'zhong',N'諥' union all select 'zhou',N'驟' union all select 'zhu',N'鑄' union all select 'zhua',N'爪' union all select 'zhuai',N'跩' union all select 'zhuan',N'籑' union all select 'zhuang',N'戅' union all select 'zhui',N'鑆' union all select 'zhun',N'稕' union all select 'zhuo',N'籱' union all select 'zi',N'漬' --漬唨 union all select 'zong',N'縱' union all select 'zou',N'媰' union all select 'zu',N'謯' union all select 'zuan',N'攥' union all select 'zui',N'欈' union all select 'zun',N'銌' union all select 'zuo',N'咗') t where word >= @word collate Chinese_PRC_CS_AS_KS_WS order by word collate Chinese_PRC_CS_AS_KS_WS ASC) else @word end) set @i = @i + 1 end return @pinyin END go --执行以下命令查看函数效果 select dbo.fn_GetPinyin('韩立刚') go --创建添加学生的存储过程 create procedure addStudent @num int as begin declare @i int; set @i=1; delete TStudent; while @num>=@i begin declare @sname varchar(40) declare @sub int set @sname=dbo.create_name(rand()) set @sub=rand()*4 insert TStudent (StudentID,Sname,sex,cardID,Birthday,Email,Class,enterTime)values ( right(replicate('0',10)+ltrim(@i),10), @sname, case when(rand()>0.5) then '男' else '女' end, convert(nvarchar(16),convert(bigint,rand()*10000000000000000)), '198'+convert(char(1),convert(int,rand()*9)+1)+'-'+convert(char(2),convert(int,rand()*11+1))+'-'+convert(char(2),convert(int,rand()*27+1)), dbo.fn_GetPinyin(@sname)+'@91xueit.com', case when(@sub<1) then '网络班' when (@sub>=1 and @sub<2) then '测试班' else '开发班' end, getdate() ) set @i=@i+1; end end --添加个学生 exec dbo.addStudent 1900 --查看添加的学生 select * from dbo.TStudent go --创建插入学生成绩的存储过程学生成绩在50-100分之间 create procedure fillSore as DECLARE @St_Num INT; DECLARE @Sb_Num INT; DECLARE @i1 INT; DECLARE @i2 INT; set @i1=1; set @i2=1; delete TScore; select @St_Num=count(*) from TStudent; select @Sb_Num=count(*) from TSubject; while @St_Num>=@i1 begin set @i2=1; while @Sb_Num>=@i2 begin insert TScore values (right(replicate('0',10)+ltrim(@i1),10),right(replicate('0',4)+ltrim(@i2),4),50+rand()*50) set @i2=@i2+1 end set @i1=@i1+1 end --插入成绩 --调用存储过程插入学生成绩 exec fillSore select * from dbo.TScore --查看三张表连接的结果 select a.*,b.*,c.* from TStudent a join TScore b on a.StudentID=b.StudentID join TSubject c on b.subJectID=c.subJectID
美国国家标准协会(ANSI)和国际标准组织(ISO)为 SQL定义了标准,微软通过用Transact-SQL和ANSI—SQL兼容,Transact-SQL还包含了几种能够增强性能的扩展。
**create** object_name
**alter** object_name
**drop** object_name
use schoolDB
create table teacher
(cust_id int ,company varchar(40),contact varchar(30),phone char(12))
go
**alter** table teacher **add** age int default 30
**grant
deny
revoke**
use schoolDB
grant select on products to public
go
块注释语句
/*
*/
/*
给学生提5分
看看还有多少不及格
*/
USE schoolDB
go
select * from dbo.TScore where mark+9<60
GO
-标准标识符
第一个字符是a-z 或A-Z
第一个字符后可以是数字,字母,或各种符号@,$,_
第一个字母是符号时表示有特殊的用途
@代表局部变量或参数
#代表临时表和存储过程
##代表一个全局临时表
-限定表示符
当对象名包含空格时,当用保留关键字被用作对象的名字时,必须使用括号和引号把限定标识符括起来
Use schoolDB
create table [order detail]
(
OrderID nvarchar(10),
OrderTime datetime
)
数字型 代表数字 int tinyint smallint bigint 十进制小数 money smallmoney decimal 浮点数和real
日期型 datetime 可以精确到0.333毫秒 small
字符型 包括char 和nchar 也包含变长字符类型varchar和nvarchar
定长字符 char(20)
变长字符 varchar(20)
Char 适合存放英文 一个字符占用1个字节
Nchar 适合存放中文 一个字符占用2个字节
二进制型 Binary和varbinary,bit代表一位的值0或1,rowversion代表数据库中唯一的8位二进制。
唯一标识 代表一个全局特殊标识符(GUID),是一个16位16进制的值。
SQL变量 包括SQL所支持的各种数据类型,但不包括text,ntext, rowversion和sql_variant这几种数据类
位图和文本(immage&text) 属于大型二进制对象结构
表 这种数据类型代表一个表结构,将一个表保存在一个字段中
游标 这种数据类型用于存储过程的编程
用户自定义数据类型 由数据库管理员生成,它基于系统数据类型,当多个表需要在一个字段存储同一类型数据时,这些字段具有相同的数据类型、长度和可控属性时,选择实用用户自定义的数据类型。
使用Declare定义局部变量 ,@局部变量作用域仅限于一个批处理中,@@全局变量在整个会话有效
use schoolDB
go
declare @sname nvarchar(11),@studentid nvarchar(20)
set @studentid ='0000000022'
select @sname=Sname from dbo.TStudent where StudentID=@studentid
select @sname as 姓名
聚集函数—对于一个集合中的值进行运算,返回一个单一的,汇总的值。
use northwind
select avg(unitprice) as AvgPrice from products
go
![(https://img-blog.csdnimg.cn/20210127170734227.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQzOTkwMzU3,size_16,color_FFFFFF,t_70)
select 'ansi:',convert(varchar(30),getdate(),102) as style
union
select 'Japanese',convert(varchar(30),getdate(),111)
union
select 'European',convert(varchar(30),getdate(),113)
go
+ - * / %
比较运算符 = <> >=
字符串联运算符 + 空字符不等于空值
逻辑运算符 and or not
表达式是各种符号和对单个数据进行操作
select mark+5 from dbo.TScore where mark<60
select dateadd(yy,4,(getdate())) 表示对当时时间加4年
select dateadd(qq,2,(getdate())) 季度
select dateadd(mm,2,(getdate())) 月
select dateadd(dd,2,(getdate())) 日
select dateadd(wk,2,(getdate())) 周
select dateadd(hh,2,(getdate())) 小时
select dateadd(mi,2,(getdate())) 分钟
select dateadd(ss,2,(getdate())) 秒
select dateadd(dy,3,getdate())) 一年中的第几天
select datediff(day,‘2005-3-4’,getdate()) 返回时间差
select datepart(day,getdate())
if 条件… else …
如:
declare @score decimal
set @score=rand()100
if (@score>60) print '*** 考试及格*****’
else print ‘**** 考试不及格*****’
case 条件 when 5 …
when 6 …
when 7 …
else … end
case when @score<60 then …
when @score>60 and @score <70 then…
else …
end
如:
declare @score int
set @score=(50+rand()*50)/10
select case @score when 5 then '**不及格**'
when 6 then '**及格**'
when 7 then '**良好**'
else '**优秀**'
end
while:
declare @times int,@a varchar(100) set @times=0 set @a='*' while (@times<10) begin print @a set @a=@a+'*' set @times=@times+1 end
declare @times int,@a varchar(100) set @times=0 set @a='*' while (@times<10) begin print @a set @a=@a+'*' set @times=@times+1 end while (@times>0) begin print @a set @a=left(@a,@times) set @times =@times -1 end
使用SQL帮助
使用管理工具产生创建表删除表修改表的SQL语句
动态构造SQL语句:
declare @tableName nvarchar(20)
set @tableName=convert(varchar(4),year(getdate()))+'年'+convert(varchar(2),month(getdate()))+'月'+convert(varchar(2),day(getdate()))+'日'
select @tableName
--动态构造SQL语句
execute ('create table' +' @tableName (studentid int,studentname nvarchar(10))')
下面是日期型转化成变长字符串,再将变长字符转化成日期型
declare @ch varchar(19)
declare @t datetime
set @t=getdate()
select @t
set @ch=convert(varchar(19),year(@t))+'-'+convert(varchar(19),month(@t))+'-'+convert(varchar(19),day(@t))
select @ch
一个使用方便的文本编辑器
代码颜色转换
带有网格或文本输出的多重查询窗口
执行脚本一部分
查询执行的信息
对象浏览器有如下功能
为对象生成脚本—生成创建对象的脚本,select insert update
执行存储过程—执行存储过程,当执行有参数的存储过程时,对象浏览器提示你输入参数的值
打开表----显示查询结果,可以编辑、插入或删除行
改变数据库中的对象
使用Transact-SQL模板
生成数据库,表,视图,索引,存储过程,统计数字和函数
管理扩展属性、连接的服务器、登陆帐号、角色和用户
声明及使用游标
定制脚本
执行Transact-SQL语句
在运行时动态构造并执行Transact-SQL语句
使用批组织一起要执行的语句
使用脚本文件保存批语句,以供日后使用
declare @dbname varchar(30),@tblname varchar(30)
set @dbname='northwind'
set @tblname='products'
execute
('use '+@dbname+' select * from '+@tblname)
Go
使用批
提交一个语句或同时提交多个语句,只有在SQL查询分析器或osql工具接受这个语句,在ODBC或ODBC API的应用程序使用go将会出现错误。SQL Server优化、编译并执行批中的语句,用户自定义的变量有效范围局限于一个批内部。
对象生成语句必须使用单独的批,批中不能同时出现的语句
Create procedure
Create view
Create trigger
Create rule as
Create default
使用脚本
使用SQL查询分析器或写字板之类的任何其它文本编辑器,编写并保存脚本,扩展名.sql
查询所有行
select * from dbo.TStudent
-- 使用where子句指定行
select Sname,sex,Email from dbo.TStudent where Sname='田育朋'
使用比较操作符 = > < >= <= <>
select * from dbo.TScore where mark<=60
使用字符比较符 like
% 0个或多个字符串
_ 任何单个的字符
[]在指定区域或集合内的任何单个字符
[^]不在指定区域或集合内的任何单个字符(除了……其他都有)
select * from dbo.TStudent where sname like '高%'
select * from dbo.TStudent where sname like '_[明,育]_'
select * from dbo.TStudent where sname like '_[^明,育]_'
模糊查询:注意%
Or and not
select * from dbo.TStudent where Sname like '高%' and sex='男' or StudentID='0000000112'
-- 查找不姓高的学生
select * from dbo.TStudent where Sname not like '高%'
--Between 70 and 80包括70 和 80
select * from dbo.TScore where mark between 70 and 80
--等价于
select * from dbo.TScore where mark>=70 and mark<=80
go
--mark>70 and mark<80
--不包括70 和80
--尽量使用between而不使用and和比较操作符表示的表达式
--如果想返回不在指定区域的行时,使用not between 。这样会降低数据查询的速度。
select * from dbo.TScore where mark not between 70 and 80
--指定时间范围
select * from dbo.TStudent where Birthday between '1983-01-01' and '1984-01-01'
select * from dbo.TStudent where Class in ('开发','网络')
-- 等价于
select * from dbo.TStudent where Class='开发' or Class='网络'
--使用in 或使用由or操作符连接起来的一系列比较操作符,SQLServer在处理他们的方式相同。不要在搜索条件结尾---使用NULL,这将返回意想不到的结果。可以使用not in,降低数据查询速度。
insert dbo.TStudent (StudentID,Sname,sex) values ('0000001901','韩立刚','男')
--查找班级为空的学生
select * from dbo.TStudent where Class is not null
--查找班级不为空的学生
select * from dbo.TStudent where Class is not null
--is null
--使用is not null来查询指定列中非空的行
asc 升序
desc降序
-- 按照底2,3即:subJectID,mark,列降序排列
select StudentID,subJectID,mark from dbo.TScore order by 2,3 desc
select StudentID,subJectID,mark from dbo.TScore order by subJectID,mark desc
distinct
select distinct Class from dbo.TStudent
如只想看Class中有几个班:
则用distinct:
select StudentID as '学号',Sname as '姓名',sex as '性别',cardID as '身份证号',
Birthday as '生日',Email as '邮件', Class as '专业',enterTime as '录入时间' from dbo.Tstudent
--- 等价于(即可去掉as)
select StudentID '学号',Sname '姓名',sex '性别',cardID '身份证号',
Birthday '生日',Email '邮件', Class '专业',enterTime '录入时间' from dbo.TStudent
符号可能是字母,数字或标识,在结果集中,他们被用作特定的值,以增加结果集的可读性。
select StudentID '学号',Sname '姓名','性别',sex '性别' from dbo.Tstudent
下列1查询结果中,年龄是计算列,(原本是没有该列的)
select StudentID as '学号',Sname as '姓名',sex as '性别',cardID as '身份证号',
Birthday as '生日',Email as '邮件', Class as '专业',enterTime as '录入时间',
Datediff(yy,Birthday,getdate()) as '年龄' from dbo.TStudent
非缓存的查询
所有查询在执行前,都需要经过一下步骤:解释、解析、优化和编译
解析----检查语句的语法是否正确
解析----校验语句中出现的对象名称是否有效,同时检查对象的所有权的权限
优化----检查是否能够使用索引并决定联合(jion)策略
编译----把查询翻译为一个可执行的表(from)
执行----把编译过程的查询要求提交并进行处理
缓存的查询
为了提高性能SQLServer能够保存编译过的查询计划供以后使用,查询计划是经过优化的指令,他指定了如何处理插叙并访问数据。
被缓存的查询保存在内存中一个叫做过程缓存的地方,在下列两种情况下,查询将被自动缓存—特定的批和自动参数化。
特殊的批-----SQL Server将为特殊的批保存查询计划,如果接下来的批和上一个批类似,SQLServer将使用缓存的计划。脚本文本必须匹配。
select * from products where unitprice = $ 12.5
select * from products where unitprice = 12.5
select * from products where unitprice = $ 13.5
go
查询语句1和3可以使用一个查询计划,但语句2必须使用另外的查询计划。
自动参数化
use library
select * from member where member_no=7890
select * from member where member_no=1234
select * from member where member_no=7890
go
4.3.2 影响性能的注意事项
尽量使用正逻辑而不是非逻辑,非逻辑操作(no between 、 not in 和not null)可能会降低查询速度,因为它要检索数据表中的所有行;
如果能够使用一个更确定的查询,就尽量避免使用关键字LIKE,使用LIKE查询,数据查询速度可能会降低;
只要有可能,尽量在搜索条件中使用精确的比较或值的域;
使用Order by 子句可能会降低数据查询速度,
7.试验A 查询数据并操作结果集
计算数据,然后返回计算出的值,并使用字段别名
通过使用字符串函数对结果集进行格式化
拆分姓名为两列
select left(Sname,1) '姓',right(Sname,2) '名' from dbo.TStudentgo
查询过程中可使用系统函数。
如何得到服务器的进程ID
sp_who 显示服务器上所有正在产生的活动
select @@Spid 如果想知道那些活动是你的
exec sp_who 56 将显示和你的服务器进程号有关的所有活动
查询运行环境信息
select user_name()
select DB_name()
select @@servername
创建多表查询的学习环境
--创建学生表 student Create table student ( studentid int, sname nvarchar(10), sex nchar(1) ) --插入学生 insert student values (1,'韩立刚','男') insert student values (2,'王景正','男') insert student values (3,'郭淑丽','女') insert student values (4,'韩旭','女') insert student values (5,'孟小飞','男') --创建成绩表 create table score ( studentid int, subjectname nvarchar(20), score decimal ) --插入成绩 insert score values (1,'英语',89) insert score values (1,'数学',59) insert score values (2,'英语',79) insert score values (2,'数学',86) insert score values (3,'英语',57) insert score values (3,'数学',67) insert score values (6,'英语',88) insert score values (6,'数学',83)
1. 查询所有学生的成绩
select a.*,b.* from student a join score b on a.studentid=b.studentid
select sname,subjectname,score from student a join score b on a.studentid=b.studentid
select a.studentid,sname,subjectname,score from student a join score b on a.studentid=b.studentid
2. 从多个表中合并数据
使用内连接
select a.*,b.* from student a join score b on a.studentid=b.studentid
等价于
select a.*,b.* from student a inner join score b on a.studentid=b.studentid
使用外连接
左外连接
select a.studentid,sname,subjectname,score from dbo.student a left join dbo.score b on a.studentid=b.studentid
右外连接
select a.*,b.* from dbo.student a right join dbo.score b on a.studentid=b.studentid
练习:
1.查找不及格同学 姓名和学科 分数
select sname,subjectname,score from dbo.student a join dbo.score b on a.studentid=b.studentid where score<60
自连接
查找到重名的学生
select a.*,b.* from dbo.student a join dbo.student b on a.sname=b.sname where a.studentid<>b.studentid
结合Order by找出满足条件的前几条记录
1. 年龄最大的前5名学生
select top 5 * from dbo.TStudent order by Birthday
2. 年龄最小的前5名学生
select top 5 * from dbo.TStudent order by Birthday desc
3. 查找网络班年龄最小的前5名学生
select top 5 * from dbo.Tstudent where Class='网络班' order by Birthday desc
将order by排序相等的所有的记录显示出来。
/* 可以在Select 语句中单独使用聚集函数,也可以与语句group by联合使用
除了count(*)函数,如果没有满足where子句的记录,则所有的聚集函数都将返回空值,Count(*)返回0
Count(*) Count(列) Sum Min max Avg
*/
统计表中有多少行
select count(*) from dbo.TStudent
–统计表中 class 列 不为空的记录数量
insert dbo.TStudent (studentID,Sname,sex) values ('0000001901','王敬正','男')
select count(Class) from dbo.TStudent
上面两个查询语句结果都一样:[第二条查询时,插入的数据并没有class]
求平均值
select avg(mark) from dbo.TScore
求最大值和最小值
select max(mark) from dbo.TScore
select min(mark) from dbo.TScore
求总和
select sum(mark) from dbo.TScore
group by–分组统计
如果使用聚集函数,则将对表中的所有记录的某个字段进行汇总,然后生成单个的值。
如果想生成多个汇总值,同时使用聚集函数和group by 语句,联合使用having和group by子句能够使结果集只包含满足条件的记录。
联合使用group by子句与having子句
分组汇总
select Class,count(*) from dbo.TStudent group by Class
select sex,count(*) from dbo.TStudent group by sex
select subJectName,avg(mark) from dbo.TSubject a join dbo.TScore b on a.subJectID=b.subJectID
group by subJectName
4. 统计每个学生的平均分
select a.StudentID,avg(mark) from dbo.TStudent a join dbo.TScore b on a.StudentID=b.StudentID
group by a.StudentID order by avg(mark)
select a.StudentID,avg(mark) from dbo.TStudent a join dbo.TScore b on a.StudentID=b.StudentID
group by a.StudentID having avg(mark)>95
条件:学科3 班级3
求: 每科 每个班 总成绩
select subJectName,Class,sum(mark) 总分from dbo.TStudent a join dbo.TScore b on a.StudentID=b.StudentID join
dbo.TSubject c on b.subJectID=c.subJectID
group by subJectName,Class
order by 总分desc
联合使用group by 子句和操作符rollup,将两列的详细信息和分组汇总
select subJectName,Class,sum(mark) from
TStudent a join TScore b on a.StudentID=b.StudentID join TSubject c on b.subJectID=c.subJectID
group by subJectName,Class with rollup
select subJectName,Class,sum(mark) 总分 from
TStudent a join TScore b on a.StudentID=b.StudentID join TSubject c on b.subJectID=c.subJectID
group by subJectName,Class with cube
使用grouping函数,可以看出哪一行是汇总值
select subJectName,grouping(subJectName),Class,grouping(Class),sum(mark) from TStudent a join TScore b on a.StudentID=b.StudentID join TSubject c on b.subJectID=c.subJectID
group by subJectName,Class with cube
4. 最佳实践
为了改善查询操作的性能,在进行汇总操作的列上进行索引
尽量避免在含有空值的字段上使用聚集函数,因为此时你的到的结果集可能并不能代表你的数据
用order by子句为结果集中的记录排序。SQL Server并不保证结果集中记录的顺序
如果可能,尽量使用rollup操作符,因为它比操作符cube的效率高得多
5. 试验A 数据分组和汇总
练习1 使用top n关键字
练习2 使用group by 和having子句
练习 3 使用rollup 和cube操作符
1.为什么使用子查询—子查询可以把一个复杂的查询分解成一系列逻辑步骤,这样就可以用一个单个的语句解决复杂的查询问题。
2.为什么使用连接而不使用子查询—执行效力差不多,子查询可能要求查询优化器执行额外的操作,比如排序,而这些操作将会影响查询的处理策略。
select StudentID,subJectID,mark-(select avg(mark) from dbo.TScore) 差距 from dbo.Tscore
select StudentID from dbo.TScore where mark-(select avg(mark) from dbo.TScore)>23
select StudentID,mark from dbo.TScore where mark-(select avg(mark) from dbo.TScore)>23
select * from dbo.TScore where subJectID=(select subJectID from dbo.TSubject where subJectName='网络管理')
等价于多表查询 多表查询效率更高
select a.* from dbo.TScore a join dbo.TSubject b on a.subJectID=b.subJectID where subJectName='网络管理'
两个结果是一样的:
找到平均分低于60分的学生学号 姓名
select StudentID,Sname from dbo.TStudent where StudentID in (select StudentID from
(select StudentID,avg(mark) 平均分from dbo.TScore group by StudentID having avg(mark)<60) as t1)
insert dbo.TStudent values ('0000001902','李维伟','男','132302197506055634','1984-3-4','liweiwei@91xueit.com','网络班',getdate())
插入学生 学号 ;姓名 性别 其他列为空
insert dbo.TStudent (StudentID,sex,Sname) values ('0000001903','男','张国强')
将学生表中网络班的学生 查询出来 插入现有表中
-- 将dbo.TStudent表中Class='网络班'的信息插入到dbo.TNetwork表中
insert dbo.TNetwork select * from dbo.TStudent where Class='网络班'
使用Select into 创建表。
将学生表中 开发班 的从学生 查询到一个新表
select StudentID,Sname,sex,Email into TDe from dbo.TStudent where Class='开发班'
删除学号是0000000020的学生
delete dbo.TStudent where StudentID='0000000020'
删除1982年以前出生的学生
delete dbo.TStudent where Birthday<'1982-1-1' and class=’网络班’
下面的例子使用一个带delete语句的连接操作,删除不及格学生
Delete 条件使用子查询
delete dbo.TStudent where StudentID in (select distinct StudentID from dbo.TScore where mark<60)
dstinct 将重复的变为不重复。
Delete 后面多表连接
delete dbo.TStudent from dbo.TStudent a join dbo.TScore b on a.StudentID=b.StudentID where mark<60
更改学生学号是0000000569的学生姓名为 韩立刚 性别 改成 男
update dbo.TStudent set Sname='韩立刚',sex='男' where studentid='0000000569'
将网络班的学生邮箱更改为 姓名拼音@network.com
update dbo.TStudent set Email=left(Email,Len(email)-12)+'@network.com' where Class='网络班'
基于其他表更新数据行
给软件测试 分数低于70分的学生加5分
使用子查询
update dbo.TScore set mark=mark+5 where mark<70 and subJectID=
(select subJectID from dbo.TSubject where subJectName='软件测试')
给软件测试 分数低于80分的学生加5分
多表连接
update dbo.TScore set mark=mark+5 from dbo.TScore a join dbo.TSubject b on a.subJectID=b.subJectID
where b.subJectName='软件测试' and mark<80
给事务中的数据加锁可阻止其他事务或查询的进行直到事务的结束
修改表可以修改数据的物理存储,同时导致事务中发生数据页的分配
如果正在被修改的数据列创建了索引,这些列的索引作为事务的一部分也被修改
数据修改语句where子句中的列的索引可以改进性能
7.最佳实践
在修改数据前先Select一下,察看修改前的数据
把列名改为别名或使用文字替换结果的值来提高计算结果的可读性。
如果不加条件delete和update将会删除或更新所有行。
8.试验A 修改数据
练习1 使用insert语句
练习2 使用带default关键字的insert语句
练习3使用带default values关键字的Insert语句
练习4 使用delete语句
练习5 使用update语句
练习6 基于其他表的数据修改表
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。