T-SQL语句大全
--跳转到SQL myDemo USE [SQL myDemo] go --声明变量id declare @id int --为变量赋值:直接赋值 set @id = 2 --将cid为3的cname值赋给变量@cn declare @cn varchar(10) --为变量赋值:查询赋值 select @cn = cname from classes where Cid = @id --输出【print:可直接输出‘字符串‘或变量】变量@cn if{} ===》if begin end print @cn --SQL Server的版本信息 print ‘版本信息 = ‘+ @@version --配置数据库,启动监听服务(SQL2008)【当监听的指定数据库内容某张表变化时就更新缓存】 alter database [SQL myDemo] set new_broker with rollback immediate alter database [SQL myDemo] set enable_broker --检测数据库是否开启监听服务【结果为0则是未启动,为1是启动状态。数据源缓存使用】 select is_broker_enabled as 是否启动 from sys.databases where name = ‘SQL myDemo‘ --生成GuId select newid() select top(3) * from students where sid not in (select top(3) sid from students) select ID,Name,Age from T_GUID INSERT INTO T_GUID (ID,NAME,AGE) select NEWID(),‘王岩‘,21 union select NEWID(),‘鹏哥‘,22 union select NEWID(),‘马金龙‘,23 select * from students where cid is null select * from rpater delete from rpater where id <> 1 and id <> 2 and id <> 4 and id <> 5 insert into classes(cnum,cname,clog) values (23,‘五年级‘,‘吼吼‘) --查询表数据 select * from dbo.students where SID = 120 and sAge = 23 --SQL注入:执行sql语句过程中,将sql语句进行拼接时含有攻击性的字符,导致数据泄漏 select * from stuInfffo where stuName = ‘‘ or 1 = 1 update stuInfffo set stuname = ‘王岩‘,stuno = 55,stuSex = ‘男‘ where stuname = ‘王岩‘ select * from students where SID = 120 select * from students where sname select * from classes select top(3) * from classes where cid not in (select top(3) cid from classes) select top(3) * from classes where cid not in (select top(4) cid from classes) --select top(3) cid from classes where cid > (select max(cid) from (select top(4) cid from classes) as classses) select top(3) * from classes where cid > (select top(1) cid from classes where cid not in (select top(3) cid from classes)) select top(4) * from classes order by cid desc select cid from classes where cnum = (select max(cnum) from classes) select * from classes where cid between 5 and 7 select sum(sid) from students where cid = 2 select * from commodity where 类别 like ‘矿%‘ update students set sName=‘杨洋‘,sAge=23,sLovely=‘篮球‘ where SID=120 --插入单行数据 --语法:insert into 表名(列名) values (值) insert into dbo.Students(sName,sAge,slovely,sclass,cid) values(‘马金龙‘,21,‘篮球‘,02,2) --插入多行数据 --语法:insert into 表名(列名) -- select 值 union -- select 值 insert into dbo.Students(sName,sAge,sClass,sLovely) select ‘张星远‘,22,‘02‘,‘篮球‘ union select ‘赵赫然‘,22,‘02‘,‘篮球‘ --将table1中的id,name值添加到table2中 --table1:id,name,set,address --table2:id,name insert into table2(id,name) select id,name from table1 where id != 100 --修改数据语法:update 表名 set 列=‘修改值‘ where 条件 update dbo.Students set sName=‘杨洋‘ where SID = 105 update dbo.Students set sAge=24 where sName=‘鹏哥‘ update dbo.Students set sClass=‘01‘ where SID = 100 or SID = 101 --删除数据语法:delete from 表名 where 条件 delete from dbo.Students where SID = 109 or SID = 110 delete from dbo.Students where 113 <= SID and SID <= 115 --删除表中所有数据[清空表数据时效率更高],不能加任何条件 truncate table students --查询数据语法:select * from 表名 select * from dbo.Students --查询为空的行 select * from dbo.Students where Cid is null --is(是),查询不为空的行 select * from dbo.Students where Cid is not null --as(重命名) select sname as 姓名 from dbo.Students --使用 = 赋值 select ‘姓名‘ = sname+‘.‘+cname from dbo.Students,dbo.Classes --限制查询:top(n) select top(2) * from dbo.Students --查询前两行 select top 50 percent * from students --按百分比查询,查询表前百分之五十的内容 --排序(小到大) select * from dbo.Students order by sAge --分组 select sname,COUNT(sname) as 次数,MAX(sid) as 最大ID from Students group by sname having COUNT(sname) > 2 select sname,count(*) from students group by sname having count(sname) > 2 --倒序(大到小):desc select * from classes order by cid desc --同时排序多个 select * from dbo.Students order by sAge,sName --返回当前日期 select GETDATE() --返回你所登陆的计算机的名字 select HOST_NAME() --替换字符串 update dbo.Students set sName = replace(‘鹏张‘,‘张‘,‘哥‘)where SID = 101 update dbo.Students set sClass = replace(sclass,‘0‘,‘00‘) --模糊查询:like select * from dbo.Students where sName like ‘张%‘ --模糊查询实现文字联想功能(例:百度搜索提示原理) select * from students where sname like ‘%[鹏龙]%‘ --in:查询指定字符的内容 select * from Classes where cLog in(‘哈哈‘) --between特定范围查询 select * from dbo.Students where SID between 116 and 118 --总和查询:sum select MAX(cname) as ‘班级‘, sum(cnum) as ‘总人数‘ from Classes --平均数:avg select avg(cnum) as ‘平均人数‘ from Classes --最大值:max select max(cname) as ‘最大人数班级‘ from Classes --最小值:min select min(cname) as ‘最大人数班级‘ from Classes --查询总行数:count select count(*) as ‘总行数‘ from Classes --查询数据库中所有表的表名 SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = ‘BASE TABLE‘ --删除、增加、修改数据表其中的一列 alter table Ware Drop column wBak -- 删除 alter table Ware Add wBak nvarchar(MAX) null default ‘老马‘ -- 增加。default 默认值 alert table ware alert column Name varchar(10) --修改字段 --插入一条数据,用最快的方式查询出该数据的ID insert into students(sName,sAge,sLovely,sClass,Cid) values(‘张三‘,23,‘足球‘,2,3) select ident_current(‘students‘) insert into students(sName,sAge,sLovely,sClass,Cid) values(‘张三‘,23,‘足球‘,2,3) select @@identity delete from students sid not in (select min(sid) from students group by sname having count(sname) > 1) select * from students select * from classes --联结查询:内联结(inner join:查询所有条件相同的内容)左联结(left join:左全右偏)右联结(right join:右全左偏) --【 on 相当于 where 】 select * from Students inner join Classes on Students.Cid = Classes.Cid and students.sid = 146 select * from Students left join Classes on Students.Cid = Classes.Cid select * from Students right join Classes on Students.Cid = Classes.Cid select * from Students cross join Classes where Students.Cid = Classes.Cid --交叉联结(同内联结) select * from Students full join Classes on Students.Cid = Classes.Cid --完整外联结 --三表联结查询 select * from Students as s,Classes as c,demos as d where s.Cid = c.Cid and s.sid = d.sid --查询“鹏哥”所借的书籍的信息 select c.cnum,c.cname from students as s, classes as c,demos as d where d.id = c.id and s.sname = ‘鹏哥‘ --分组查询 select sAge,COUNT(sAge) as 年龄个数 from Students group by sAge having COUNT (sAge) > 0 select sAge as 年龄 from Students group by sAge select sname,COUNT(sname) as 次数,MAX(sid) as 最大ID from Students group by sname having COUNT(sname) > 2 select * from students, (select sname,COUNT(sname) as 次数,MAX(sid) as ID from Students group by sname having COUNT(sname) > 2) as a where students.sID <> 129 AND students.sname = ‘马金龙‘ --s.sid AND s.sid = a.ID select sage from students group by sage select sname,COUNT(sname) from students group by sname having count(sname) > 1 delete top(2) from students where sid not in (select top(10) sid from students) select id from rpater where name = ‘张三‘ delete from demos where sid = 117 select * from demos where cname = ‘五年三班‘ select * from Classes inner join demos on Classes.cname = demos.cname select * from demos where sid = 116 select * from t_Dropdown1 as d,t_Dropdown2 as r,t_Dropdown3 as o where d.id = r.pid and r.pid = o.pid delete from rpater where id > 5 select * from students where sName = ‘张三‘ select sname from students insert into students(sname,sage,slovely,sclass,cid) select ‘王岩‘,21,‘篮球‘,2,2 union select ‘赵帅‘,21,‘篮球‘,2,2 union select ‘张鹏‘,21,‘篮球‘,2,2 union select ‘鹏哥‘,21,‘篮球‘,2,2 union select ‘马金龙‘,21,‘篮球‘,2,2 union select ‘马金龙‘,21,‘篮球‘,2,2 union select ‘王岩‘,21,‘篮球‘,2,2 union select ‘马金龙‘,21,‘篮球‘,2,2 union select ‘张鹏‘,21,‘篮球‘,2,2 insert into T_ChuanZhiBoKe(Name,Pwd,ErrorTimes,ErrorTime) values(‘张三‘,‘789‘,2,(getdate())) select * from T_ChuanZhiBoKe update T_ChuanZhiBoKe set ErrorTimes = ErrorTimes + 1,ErrorTime = (getdate()) where id = 3 update T_ChuanZhiBoKe set ErrorTime = (getdate()) where id = 2 --取得表中不重复的值 select * from students where sid in (select max(sid) from students group by sName) --删除表中name重复的值,只留一条 delete from students where sid not in (select min(sid) from students group by sname) --查询表A(id,name)中name重复三次以上的记录,并删除重复记录,只留id最大的 delete from students where sname in (select sname from students group by sname having count(sname) > 1) and sid not in (select max(sid) from students group by sname having count(sname) > 1) select * from stuInfffo --查询和学号’s25301’的这位同学性别相同的所有同学的姓名和年龄 select stuname,stuAge from stuInfffo where stuSex in (select stusex from stuInfffo where stuno = ‘s25301‘) --查询时间差 SELECT DATEDIFF(MONTH,‘2012-01-01 0:0:0‘,getdate()) select top(2) * from students where sid > (select max(sid) from (select top(6) sid from students) as a) select top(2) * from classes where cid not in (select top(5) cid from classes) delete from classes where cid in (select top(2) cid from classes where cid not in (select top(5) cid from classes))
--创建包含父级子级的表,查询显示为父级-子级-子级;父级-子级-子级
select *, case when PID = 0 then ID else PID end as TID FROM MianShiTi ORDER BY TID,PID select * from MianShiTi
--自定义函数【标量函数;内嵌表值函数;多声明表值函数】:
--能在select等语句中直接使用自定义函数,存储过程不行;
--自定义函数可以调用其它函数,也可以调用自己( 结果集需要通过递归等方法得到时,可以使用函数,函数比较灵活);
--只查询,不能修改数据库的状态
--只能调用扩展存储过程,但在sqlserver2008的后续版本将不再支持扩展存储过程
create function biaoliang(@age int,@cid int) returns int as begin return @age * @cid end go --自定义函数的调用【SQL myDemo:数据库名称】 select [SQL myDemo].dbo.biaoliang(23,2)
触发器
if(object_id(‘tgr_students_insert‘,‘tr‘) is not null)--判断是否有名称为tgr_students_insert的触发器 drop trigger tgr_students_insert --如果有则删除该触发器 go alter trigger tgr_students_insert --创建触发器tgr_students_insert on students --当对students表进行insert插入操作时执行as之后的T-SQL语句 for insert as declare @id int,@name varchar(20),@temp int; --声明局部变量 select @id = sid,@name = sname from inserted; --插入语句时生成一张数据库临时表(inserted),将新插入语句的sid,sname值赋给变量@id,@name set @name = @name; -- + convert(varchar,@id); --重新赋值 set @temp = @id / 2; insert into classes values(18,@name,@temp,@id); --向students表内插入语句时同时向classes表插入一条语句 print ‘添加学生成功!‘; go insert into students(sname,sage,slovely,sclass,cid) values(‘张三‘,23,‘CS‘,2,2)
索引:
USE [SQL myDemo] GO if exists(select name from sysindexes where name = ‘LX_suoyin‘) drop index students.LX_suoyin create NONCLUSTERED index LX_suoyin on students(sage) WITH FILLFACTOR= 30 GO select * from students with(index=LX_suoyin) where sage between 21 and 23
横表纵表相互转换
--纵表转换横表 select * from TableA select Name, -- 遍历每列学生 sum(case Course when ‘语文‘ then Grade -- 如果科目是语文则返回语文成绩,否则返回0 else 0 end) as 语文, sum(case Course when ‘数学‘ then Grade else 0 end) as 数学, sum(case Course when ‘化学‘ then Grade else 0 end) as 化学, sum(case Course when ‘物理‘ then Grade else 0 end) as 物理, sum(case Course when ‘外语‘ then Grade else 0 end) as 外语 from TableA group by Name --横表转纵表 select ‘外语‘,外语 from TableB select Name,‘语文‘ as 科目, 语文 as 成绩 from TableB union all select Name,‘数学‘ as 科目, 数学 as 成绩 from TableB union all select Name,‘外语‘ as 科目, 外语 as 成绩 from TableB -- ‘外语‘ as 科目 相当于 将分数转换为外语科目 ORDER BY Name,科目 DESC -- 外语 as 成绩 等于把外语字段转换为成绩字段
纵表
横表
建库建表建约束 ====== 视图
--创建数据库 if exists(select * from sys.databases where name=‘stulan‘) drop database stulan create database stulan on ( name = ‘stulan_data‘, filename = ‘E:\项目练习\stulan_data.mdf‘, size = 3mb,--初始大小 maxsize = 50mb,--文件增长的最大值 filegrowth = 5mb--文件增长率 ) go --创建表 use stulan go if exists(select * from sys.objects where name=‘t_stoInfo‘) drop table t_stoInfo go create table t_stoInfo ( id int identity(1,1) not null,--自增列 name varchar(20) not null, age int not null, [address] varchar(max) not null, stuNo char(6) not null ) go --创建表 if exists(select * from sys.objects where name=‘t_stuMarks‘) drop table t_stuMarks go create table t_stuMarks ( id int identity(1,1) not null, stuNo char(6) not null, shuxue varchar(20) null, yuwen varchar(20) null ) go --创建约束 --主键约束:要求主键列数据唯一,并且不允许为空 alter table t_stoInfo add constraint pk_stuNo primary key(stuNo) --默认约束:某列的默认值 alter table t_stoInfo add constraint df_address default(‘地址不详‘) for address --检查约束:某列的取值范围限制 alter table t_stoInfo add constraint ck_age check(age between 15 and 50) --唯一约束:要求该列唯一,允许为空,但只能出现一个空值 alter table t_stoInfo add constraint uq_id unique(id) --外键约束:用于两表间建立关系,需要指定引用主表的那列 alter table t_stuMarks add constraint fk_stuNo foreign key(stuNo) references t_stoInfo(stuNo) go --事务 begin transaction -- 开始事务 declare @errorsum int --定义变量 set @errorsum = 0 --初始化变量 update Students set sAge = sAge + 12 where sName = ‘张鹏‘ set @errorsum = @errorsum + @@error --累计是否有错误 if @errorsum <> 0 begin print ‘错误‘ rollback transaction --回滚事务 end else begin print ‘正确‘ commit transaction --提交事务 end select * from Students --创建视图 create view view_Display as select stuName,stuNo,(select writtenExam from stuMarks where stuMarks.stuNo = stuInfffo.stuNo) as writtenExam from stuInfffo EXEC sp_tables EXEC sp_columns students EXEC xp_cmdshell ‘dir d:\‘ alter proc proc_lantian @cNum int, @cName varchar(10), @cLog varchar(10) as select @cNum = cNum,@cName = cname,@cLog = clog from classes EXEC(‘select clog from classes‘) go alter proc proc_lantian @status int, --接收操作参数 @outSta int output --传出参数 as begin if @status=1 begin select*from students end else if @status=2 begin select*from classes end set @outSta = @status EXEC proc_lantian @outSta = 1 end select * from classes
分页存储过程
alter proc proc_zp @a int,--每页几条 @b int --第几页 as select top(@a) * from fenye where id not in(select top(@a*@b) id from fenye) GO EXEC proc_zp 4,0
存储过程实例
--根据不同的参数查询不同的表 alter proc proc_lantian @tablename varchar(20) as declare @str varchar(max) set @str = N‘ select * from ‘ + @tablename EXEC(@str) GO EXEC proc_lantian ‘classes‘ --根据不同的参数查询不同的列及设置条件 alter proc proc_lantian @columnname varchar(20) = N‘ * ‘, @table varchar(20), @where varchar(20)=‘‘ as declare @col varchar(max),@cc varchar(max) set @cc = N‘ where ‘ + @where if @where = ‘‘ begin set @cc = ‘‘ end set @col = N‘ select ‘ + @columnname + N‘ from ‘ + @table + @cc EXEC(@col) GO EXEC proc_lantian @table = ‘students‘,@where = ‘sid = 120‘ ----------------------------------------------------------------- alter proc proc_lantian @columnname varchar(20) = N‘ * ‘, @rows varchar(50), @where varchar(100), @orderrows varchar(50), @orderbyte int as declare @col varchar(max),@cc varchar(max) set @cc = N‘ where ‘ + @where if @where = ‘‘ begin set @cc = ‘‘ end set @col = N‘ select ‘ + @columnname + N‘ from ‘ + @table + @cc EXEC(@col) GO EXEC proc_lantian @table = ‘students‘,@where = ‘sid = 120‘ select * from classes where Cid > 2 select * from T_Readers alter proc proc_reader @Name varchar(10) [email protected] int as --select BookNum from T_Readers where readerName = @Name if (select BookNum from T_Readers where readerName = @Name) = 0 begin print(‘该同学没有借阅‘) end else begin select readerName,StudentNum,TeleNum,BookNum from T_Readers where readerName = @Name end GO EXEC proc_reader ‘鹏哥‘ select * from [User] alter proc proc_Login @User varchar(20), @Pwd varchar(20) [email protected] int as select * from [User] where mName = @User and mPwd = @Pwd --delete from [User] where mID = @ID Go EXEC proc_Login ‘徐囡‘,‘1122‘ --查询表中同学姓名,如果存在返回1,否则返回0 alter proc proc_Name @Name varchar(10) as declare @cou int set @cou = (select count(*) from students where sname = @Name) if @cou > 0 begin print(1) end else begin print(0) end GO EXEC proc_Name ‘王‘ ------ alter proc proc_shuchu @shuchu int output as select count(*) from students GO EXEC proc_shuchu @shuchu output
时间: 2024-10-18 17:50:29