一、插入语句

1. 普通插入

insert into tableA(字段1,字段2,字段3)values(字段值1,字段值2,字段值3)
例:

insert into tableA(
	userName,
	userSex,
	userPhone
)values(
	'张三',
	'男',
	'18812345678'
)

2. 表数据查询(复制)插入

insert into tableA(字段1,字段2,字段3)select (字段4,字段5,字段6) from tableB

insert into tableA(
	userName,
	userSex,
	userPhone
)select
	memberName,
	memberSex,
	memberPhone
 from tableB
 where ……

二、查询语句

1. 所有数据查询

select 字段1,字段2,字段3 from tableA where ……
例:

select
	userName,
	userSex,
	userPhone
from tableA
where ……

2. 根据某条件查询前多少条数据

select top n 字段1,字段2,字段3 from tableA where ……
(n为数据条数)
例(前10条数据):

select
	top 10
	userName,
	userSex,
	userPhone
from tableA
where ……
order by userName

三、更新语句

1. 单表数据更新

update tableA set 字段1=‘字段值1’,字段2=‘字段值2’,字段3=‘字段值3’ where……
例:

update tableA
set userName='李四',
userSex='男',
userPhone='13012345678'
where userName='张三'

2. 多表联合数据更新

update a set a.字段1=b.字段4,a.字段2=b.字段5,a.字段3=b.字段6
from tableA a left join tableB b on a.userId=b.userId
where……
例:

update a
set a.userName=b.userName,
a.userSex=b.userSex,
a.userPhone=b.userPhone
from tableA a 
left join tableB on a.userId=b.userId
where ……

四、删除语句

delete from tableA where ……
例:

delete from tableA where userName='张三'

五、case when……else

case when 条件1 then ……when 条件2 then……else……end
例:

select
	case when sexFlag=0 then '女'
	when sexFlag=1 then '男'
	else '未识别'
	end userSex
from tableA

六、left join(左关联查询)

结果集返回左表(tableA)所有数据,若左表存在、右表(tableB)无数据则右表数据返回null
例:

select
	a.userName,--tableA表中人员姓名
	b.userOrderId--tableB中人员订单号,若不存在则返回null
from tableA a
left join tableB b on a.userId=b.userId

七、right join(右关联查询)

结果集返回右表(tableB)所有数据,若右表存在、左表(tableA)无数据则左表数据返回null
例:

select
	a.userName,--tableA表中人员姓名,若不存在则返回null
	b.userOrderId--tableB中所有订单号
from tableA a
right join tableB b on a.userId=b.userId

八、inner join(内关联查询)

结果集返回左表(tableA)和右表(tableB)都存在的数据
例:

select
	a.userName,--tableA表中人员姓名
	b.userOrderId--tableB中所有订单号
from tableA a
inner join tableB b on a.userId=b.userId

九、like

模糊条件查询,查询某个字段值包含某一字符串的结果集
例(查询姓名中含有【国】字的所有人员信息):

select
……
from tableA
where userName like '%国%'

十、concat

字符换拼接组合
例(姓名/性别/手机号组合为一个字段):

select
--返回:张三-男-18812345678
CONCAT(userName,'-',userSex,'-',userPhone) as userInfo
from tableA
where ……

十一、charindex

判断某字段值是否包含某一字符串,若包含则返回字符串的位置(大于0),若不存在则返回0,一般用于筛选条件
例(查询姓名中包含【国】字的所有人员信息):

select
……
from tableA
where charindex('国',userName)>0

十二、substring

截取字符串
例:

select
--手机号第4位开始截取,共截取4位
substring(userPhone,4,4)
from tableA

总结

以上,即是SQLServer的一些很简单的基础语法,仅供初级阶段参考学习。
一直相信即使再复杂的SQL也只是基础语法的复杂组合,就像不管多少位的两个数字相乘,其实本质都是10以内的乘法而已……

Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐