T-SQL语句大全
--跳转到SQL myDemo
USE [SQL myDemo]
go --声明变量id
declare @id int
--为变量赋值:直接赋值
set @id =
--将cid为3的cname值赋给变量@cn
declare @cn varchar()
--为变量赋值:查询赋值
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() * from students where sid not in (select top() sid from students) select ID,Name,Age from T_GUID
INSERT INTO T_GUID (ID,NAME,AGE)
select NEWID(),'王岩', union
select NEWID(),'鹏哥', union
select NEWID(),'马金龙', select * from students where cid is null select * from rpater
delete from rpater where id <> and id <> and id <> and id <>
insert into classes(cnum,cname,clog) values (,'五年级','吼吼')
--查询表数据
select * from dbo.students where SID = and sAge =
--SQL注入:执行sql语句过程中,将sql语句进行拼接时含有攻击性的字符,导致数据泄漏
select * from stuInfffo where stuName = '' or =
update stuInfffo set stuname = '王岩',stuno = ,stuSex = '男' where stuname = '王岩'
select * from students where SID =
select * from students where sname
select * from classes
select top() * from classes where cid not in (select top() cid from classes)
select top() * from classes where cid not in (select top() cid from classes)
--select top() cid from classes where cid > (select max(cid) from (select top() cid from classes) as classses)
select top() * from classes where cid > (select top() cid from classes where cid not in (select top() cid from classes))
select top() * from classes order by cid desc
select cid from classes where cnum = (select max(cnum) from classes) select * from classes where cid between and
select sum(sid) from students where cid =
select * from commodity where 类别 like '矿%'
update students set sName='杨洋',sAge=,sLovely='篮球' where SID= --插入单行数据
--语法:insert into 表名(列名) values (值)
insert into dbo.Students(sName,sAge,slovely,sclass,cid) values('马金龙',,'篮球',,) --插入多行数据
--语法:insert into 表名(列名)
-- select 值 union
-- select 值
insert into dbo.Students(sName,sAge,sClass,sLovely)
select '张星远',,'','篮球' union
select '赵赫然',,'','篮球' --将table1中的id,name值添加到table2中
--table1:id,name,set,address
--table2:id,name
insert into table2(id,name)
select id,name from table1 where id != --修改数据语法:update 表名 set 列='修改值' where 条件
update dbo.Students set sName='杨洋' where SID =
update dbo.Students set sAge= where sName='鹏哥'
update dbo.Students set sClass='' where SID = or SID = --删除数据语法:delete from 表名 where 条件
delete from dbo.Students where SID = or SID =
delete from dbo.Students where <= SID and SID <=
--删除表中所有数据[清空表数据时效率更高],不能加任何条件
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() * from dbo.Students --查询前两行
select top 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) >
select sname,count(*) from students group by sname having count(sname) > --倒序(大到小):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 =
update dbo.Students set sClass = replace(sclass,'','') --模糊查询: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 and --总和查询: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() --修改字段 --插入一条数据,用最快的方式查询出该数据的ID
insert into students(sName,sAge,sLovely,sClass,Cid) values('张三',,'足球',,) select ident_current('students')
insert into students(sName,sAge,sLovely,sClass,Cid) values('张三',,'足球',,) select @@identity delete from students sid not in (select min(sid) from students group by sname having count(sname) > )
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 =
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) >
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) >
select * from students, (select sname,COUNT(sname) as 次数,MAX(sid) as ID from Students group by sname having COUNT(sname) > ) as a where students.sID <> 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) >
delete top() from students where sid not in (select top() sid from students)
select id from rpater where name = '张三'
delete from demos where sid =
select * from demos where cname = '五年三班'
select * from Classes inner join demos on Classes.cname = demos.cname
select * from demos where sid =
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 >
select * from students where sName = '张三'
select sname from students
insert into students(sname,sage,slovely,sclass,cid)
select '王岩',,'篮球',, union
select '赵帅',,'篮球',, union
select '张鹏',,'篮球',, union
select '鹏哥',,'篮球',, union
select '马金龙',,'篮球',, union
select '马金龙',,'篮球',, union
select '王岩',,'篮球',, union
select '马金龙',,'篮球',, union
select '张鹏',,'篮球',, insert into T_ChuanZhiBoKe(Name,Pwd,ErrorTimes,ErrorTime) values('张三','',,(getdate()))
select * from T_ChuanZhiBoKe
update T_ChuanZhiBoKe set ErrorTimes = ErrorTimes + ,ErrorTime = (getdate()) where id =
update T_ChuanZhiBoKe set ErrorTime = (getdate()) where id = --取得表中不重复的值
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) > ) and sid not in (select max(sid) from students group by sname having count(sname) > ) 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() * from students where sid > (select max(sid) from (select top() sid from students) as a)
select top() * from classes where cid not in (select top() cid from classes)
delete from classes where cid in (select top() cid from classes where cid not in (select top() cid from classes))

--创建包含父级子级的表,查询显示为父级-子级-子级;父级-子级-子级

select *,
case
when PID = 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(,)

触发器

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(),@temp int; --声明局部变量
select @id = sid,@name = sname from inserted; --插入语句时生成一张数据库临时表(inserted),将新插入语句的sid,sname值赋给变量@id,@name
set @name = @name; -- + convert(varchar,@id); --重新赋值
set @temp = @id / ;
insert into classes values(,@name,@temp,@id); --向students表内插入语句时同时向classes表插入一条语句
print '添加学生成功!';
go insert into students(sname,sage,slovely,sclass,cid) values('张三',,'CS',,)

索引:

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=
GO
select * from students with(index=LX_suoyin) where sage between and

横表纵表相互转换

--纵表转换横表
select * from TableA select Name, -- 遍历每列学生
sum(case Course
when '语文' then Grade -- 如果科目是语文则返回语文成绩,否则返回0
else
end) as 语文,
sum(case Course
when '数学' then Grade
else
end) as 数学,
sum(case Course
when '化学' then Grade
else
end) as 化学,
sum(case Course
when '物理' then Grade
else
end) as 物理,
sum(case Course
when '外语' then Grade
else
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(,) not null,--自增列
name varchar() not null,
age int not null,
[address] varchar(max) not null,
stuNo char() 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(,) not null,
stuNo char() not null,
shuxue varchar() null,
yuwen varchar() 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 and ) --唯一约束:要求该列唯一,允许为空,但只能出现一个空值
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 = --初始化变量
update Students set sAge = sAge + where sName = '张鹏'
set @errorsum = @errorsum + @@error --累计是否有错误 if @errorsum <>
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(),
@cLog varchar()
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=
begin
select*from students
end
else
if @status=
begin
select*from classes
end
set @outSta = @status
EXEC proc_lantian @outSta =
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 ,

存储过程实例

--根据不同的参数查询不同的表
alter proc proc_lantian
@tablename varchar()
as
declare @str varchar(max)
set @str = N' select * from ' + @tablename
EXEC(@str)
GO
EXEC proc_lantian 'classes' --根据不同的参数查询不同的列及设置条件
alter proc proc_lantian
@columnname varchar() = N' * ',
@table varchar(),
@where varchar()=''
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() = N' * ',
@rows varchar(),
@where varchar(),
@orderrows varchar(),
@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 >
select * from T_Readers alter proc proc_reader
@Name varchar()
--@BookNum int
as
--select BookNum from T_Readers where readerName = @Name
if (select BookNum from T_Readers where readerName = @Name) =
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(),
@Pwd varchar()
--@ID int
as
select * from [User] where mName = @User and mPwd = @Pwd
--delete from [User] where mID = @ID
Go
EXEC proc_Login '徐囡','' --查询表中同学姓名,如果存在返回1,否则返回0
alter proc proc_Name
@Name varchar()
as
declare @cou int
set @cou = (select count(*) from students where sname = @Name)
if @cou >
begin
print()
end
else
begin
print()
end
GO
EXEC proc_Name '王' ------
alter proc proc_shuchu
@shuchu int output
as
select count(*) from students
GO
EXEC proc_shuchu @shuchu output

Sql Server语句大全的更多相关文章

  1. SQL SERVER 语句大全

    ·SQL的简单查询实例教程关键词:SQL语句大全 中文网 整理编辑,经典SQL语句大全(SQL语句大总结),欢迎网友投稿 下列语句部分是Mssql语句,不可以在access中使用.SQL分类:DDL— ...

  2. 经典实用SQL Server语句大全总结(一)

    简要介绍基础语句:1.说明:创建数据库CREATE DATABASE database-name2.说明:删除数据库drop database dbname3.说明:备份sql server--- 创 ...

  3. 测试常用SQL注入语句大全

    转载自Cracer,标题:<渗透常用SQL注入语句大全>,链接http://www.xxxx.com/?p=2226 1.判断有无注入点 整形参数判断 1.直接加' 2.and 1=1 3 ...

  4. (转)经典SQL查询语句大全

    (转)经典SQL查询语句大全 一.基础1.说明:创建数据库CREATE DATABASE database-name2.说明:删除数据库drop database dbname3.说明:备份sql s ...

  5. T-SQL:SQL Server-SQL语句大全经典

    ylbtech-SQL Server-Doc-Help:SQL Server-SQL语句大全经典 SQL Server 流程控制中的 While 语句. 1,SQL语句大全经典返回顶部 .说明:创建数 ...

  6. SQL SERVER 函数大全[转]

    SQL Server 函数大全 一旦成功地从表中检索出数据,就需要进一步操纵这些数据,以获得有用或有意义的结果.这些要求包括:执行计算与数学运算.转换数据.解析数值.组合值和聚合一个范围内的值等. 下 ...

  7. 注入学习1:SQL注入语句大全

    学习背景 之前做了xss预防,以及些许的注入预防了,但是不够全面,如果还是搜集了下一些常用的注入手段,以此用来进行更好的预防. 什么是注入 一般来说,SQL注入一般存在于形如:HTTP://xxx.x ...

  8. SQL查询语句大全集锦

    SQL查询语句大全集锦 一. 简单查询 简单的Transact-SQL查询只包括选择列表.FROM子句和WHERE子句.它们分别说明所查询列.查询的 表或视图.以及搜索条件等. 例如,下面的语句查询t ...

  9. sql注入语句大全

    sql注入语句大全--是否存在xp_cmdshell and 1=(select count(*) from master.dbo.sysobjects where xtype = 'x' and n ...

随机推荐

  1. Oracle视图 create View

    视图是一种虚表,使用CREATE VIEW语句来定义视图,该视图是基于一个或多个表或视图的逻辑表.一个视图本身不包含任何数据, 视图所基于的表称为基表. 视图就相当于一条select 语句,定义了一个 ...

  2. popwindow+动画

    布局: main: <Button android:id="@+id/btn" android:layout_width="match_parent" a ...

  3. Linux下提权常用小命令

    有些新手朋友在拿到一个webshell后如果看到服务器是Linux或Unix操作系统的就直接放弃提权,认为Linux或Unix下的提权很难,不是大家能做的,其实Linux下的提权并没有很多人想象的那么 ...

  4. 对于EMC DAE、DPE、SPE、SPS的解释

    对于EMC DAE.DPE.SPE.SPS的解释: DAE: Disk Array Enclosure 单一的磁盘扩展单元 CX200/CX300/CX400/CX500CX600/CX700 DPE ...

  5. 使用 Windows PowerShell 实现 Web UI 自动化 (转)

    转自 https://msdn.microsoft.com/zh-cn/magazine/cc337896.aspx

  6. 海思编译链编译出现__aeabi_unwind_cpp_pr1重定义怎么回事

    1.用arm-hisiv100nptl-linux-gcc编译代码,结果发现报错,__aeabi_unwind_cpp_pr1重定义,在librt.a先定义,使用的海思芯片是hi3520d. 2.本来 ...

  7. pandas(三)

    合并数据集: 创建一个能创建dataframe的函数 def make_data(cols,ind): data={c:[strc(c)+str(i) for i in ind] for c in c ...

  8. 快递单号自动识别接口API-trackingmore

    一.快递单号自动识别接口功能说明 (1)PC电脑端.移动APP或者自建网站集成物流查询功能时,只需要用户输入单号即可,不需要输入快递公司. (2)此接口可以配合Trackingmore的快递查询API ...

  9. 大疆2019校招FPGA笔试总结

    1.对于同步fifo,每100个cycle可以写入80个数据,每10个cycle可以读出8个数据,fifo的深度至少为? 写时钟频率 w_clk, 读时钟频率 r_clk, 写时钟周期里,每B个时钟周 ...

  10. 创建docker公共仓库

    1.注册公共仓库的账号 https://hub.docker.com 账号:user-a 密码:pwd 2.Linux中登录docker公共仓库 docker login 3.上传一个docker镜像 ...