--概要:SqlService常用语句
--设计者:DuanXuWen
--版本:0.1
--修改者:
--修改时间:
create table #table1
(
id int identity(1,1), --主键自增
name varchar(20)
)
insert into #table1 values('哈哈')
insert into #table1 values('嘻嘻')
insert into #table1 values('呵呵')
insert into #table1 values('嘿嘿')
select * from #table1
create table #table2
(
id int identity(1,1),
table1_id int,
height decimal(20,5)
)
insert into #table2 values(1,1.345)
insert into #table2 values(2,1.245)
insert into #table2 values(3,1.654)
insert into #table2 values(5,1.654)
insert into #table2 values(6,null)
select * from #table2
--①【join、left join、right join、inner join、full join】
--join 如果表中有至少一个匹配,则返回行
select * from #table1 a
join #table2 b on a.id = b.table1_id
--left join 即使右表中没有匹配,也从左表返回所有的行
select * from #table1 a
left join #table2 b on a.id = b.table1_id
--right join 即使左表中没有匹配,也从右表返回所有的行
select * from #table1 a
right join #table2 b on a.id =b.table1_id
--inner join内连接
select * from #table1 a
inner join #table2 b on a.id = b.table1_id
--full join 只要其中一个表中存在匹配,就返回行
select * from #table1 a
full join #table2 b on a.id = b.table1_id
--②【union、union all】
--union 去重
select * from #table1 a
inner join #table2 b on a.id = b.table1_id
union
select * from #table1 a
full join #table2 b on a.id = b.table1_id
--union all 所有
select * from #table1 a
inner join #table2 b on a.id = b.table1_id
union all
select * from #table1 a
full join #table2 b on a.id = b.table1_id
--③【round】
--保留两位小数
select round(height,2) as round2,height from #table2
--④【avg】
--获取平均值
select avg(height) from #table2
--⑤【coalesce】
--身高为null的默认1.83
select coalesce(null,height,1.83) 默认身高,height 身高 from #table2
--⑥【str】
--身高保留两位小数
select str(height,5,2) as 长度5保留2小数,height as 原始 from #table2
--身高不保留小数
select str(height) as 不保留小数,height as 原始 from #table2
--⑦【ltrim、rtrim】
--ltrim函数去掉左边空格
select ltrim(height) from #table2
--rtrim函数去掉右边空格
select rtrim(height) from #table2
--⑧【reverse】
--逆向显示
select reverse(height) as 逆向,height 顺向 from #table2
--⑨【quotename】
--name加[]
select quotename(name) as [姓名] from #table1
--⑩【abs】
--绝对值
select abs(isnull(height,-123.3)) as 绝对值,isnull(height,-123.3) as 原始值 from #table2
---------------------------------------------------
drop table #table1
drop table #table2