一,插入单条数据
insert into 表名(列名,列名...)value(值,值...) value的值加括号
insert into 表名(列名,列名...)select 值,值.... select的值不加括号
二,插入多条数据
insert into 表名(列名)value(值),(值),(值)
insert 表名(列名,列名,列名)
select ‘值’,‘值’,‘值’ union
select ‘值’,‘值’,‘值’ union
select ‘值’,‘值’,‘值’
union去重复插入,union on允许重复插入
三,将一张表的所有数据复制倒另一张
insert into 表(列) select 源列 from 源表
修改
update Test set Name="" where id=5 ( and 并且| or或者 )
删除
delete from Test where Id=5
查询 别名 三种方式
select UserId as 用户编号,UserName 用户名, 年龄 = Age
from Test
order by UserId asc升序 (desc降序)
或者排序 先用户ID后年龄
order by UserId asc, Age desc
或者
order by Age,UserId
查询前数据100%的 (100percent)
select top 100 percent * from Test
聚合函数
select count(*) from Test
sum求和 avg求平均 max最大 min最小
group by通过班级ID查询不同班级ID的个数
select id,count(*) 用户数 from UserInfo
group by 班级Id
公式:
---select ... where ... group by .... order by ...
group by如果有where,一定在where的后面
select 出现的列名,必须出现在goup by之后或者包含在聚合函数中
inner join只查出相匹配的数据结果,不匹配就不显示
---inner join on 后面接关联条件
select userid,username, u.Userid from A表.u
inner join B表.d on d.Depid = u.Userid
(第二种隐式链接,inner join换为逗号,on换为where)
select userid,username, u.Userid from A表.u,B表.d where d.Depid = u.Userid
left join on 返回左表所有的行,右表没有匹配上就显示null
全连接 查出两个表所有的数据,没有联系的另起一行
select * from 表A u full outer join 表B d on u.depID =d.DeptId
交叉查询(cross join 不能要on) 表A4条数据,表B4条数据,可以查出16条数据
select * from 表A u cross join 表B d where...
存储过程
create proc 存储过程名称
@userid int, ----需要传入的参数
@username varchar(50) ----需要传入的参数
AS
begin
----需要执行的sql语句
end
go
调用存储过程
exec 存储过程名称
删除存储过程
drop proc 存储过程名称