代码所用表(表名:first,second,new_table)
本篇不是详细介绍 T-SQL 的语法,而是总结常用的 T-SQL 语句
declare @id int --声明
set @id = 11 --赋值
select @id as showId
% 表示匹配零个或者多个字符
select cname from first where cname like '张%'
_ 表示匹配一个字符
select cname from first where cname like '张_'
[ ] 表示在某一个范围内的字符
select cid from first where cid like '[0-3]'
[ ^] 表示不在某一个范围内的字符
select cid from first where cid like '[^0-3]'
select cname = substring(cname,1,1) from first
datediff():返回日期之差
select cname as 名字,年龄 = datediff(year,cbirthday,getdate()) from first
a 是要转换的数据类型,b 是被转换的数据类型
declare @number int
set @number = 3
select convert(char(1),@number) as 转换后
select count(*) as 行数,avg(convert(int,cage)) as 平均年龄,max(cbirthday) as
最晚出生年月,sum(cid) as id的和 from first
if … else …
declare @number_1 int ,@number_2 int
select @number_1 = 1,@number_2 = 2
if @number_1 > @number_2
print @number_1
else
print @number_2
while
declare @x int
select @x = 3
while @x = 3
begin
print @x
end
insert 语句:向某个表中插入数据
insert into first values(9,'insert_into',8888,'2005-10-10')
--因为出生日期是 date 类型,需要插入字符类型隐式转换
select into:把一张表的内容插入一张新表(该表未被创建)
select *
into new_table
from first
where cid > 0
select * from new_table
new_table 表被创建
新表的内容
insert into:从一张表向另一张表(该表已经存在)插入数据
PS:两张表的属性类型必须一样
insert into new_table
select *
from first
select * from new_table
因为之前插入过数据(在 select into 中插入过,所以再次插入是两倍的相同数据)
update first
set cid = 100
where cid = 2
delete from first where cid = 100
select cid from first
select distinct cname,* from first
-- 去掉了 cname 中重复的元素
select top 3 * from first
select top 3 percent * from first
select * from first
union
select * from new_table
使用 in 来筛选
select * from first where cid in (1,2)
select * from first order by cage asc
PS:group by 在 order by 前面
select cname from first group by cname
select cname from first group by cname having cname like '张%'
内连接
select * from first inner join second on first.cid = second.cid
外连接(此处演示左连接,此外还有右连接和完全外连接)
select * from first left join second on first.cid = second.cid
select a.cid ,b.cage from first a join first b on a.cid = b.cage
自连接的实现:通过 from 子句构造同一个表的两个实例 a,b,通过 a,b来调用相关列
SQL 之 自连接
select cid from first where cid = (select cid from second where cid =1)