关于T-SQL语言,下列说法正确的是句可以怎么分类?

前言代码所用表(表名: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]'
查询的结果常用的字符串函数substringselect cname = substring(cname,1,1) from first
日期函数datediff():返回日期之差select cname as 名字,年龄 = datediff(year,cbirthday,getdate()) from first
查询结果转换数据类型函数convert(a,b):强制类型转换a 是要转换的数据类型,b 是被转换的数据类型declare @number int
set @number = 3
select convert(char(1),@number) as 转换后
聚合函数avg,max,sum,count(*)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
whiledeclare @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
数据的查询去掉重复值
SQL SELECT DISTINCT 语句
select distinct cname,* from first
-- 去掉了 cname 中重复的元素
返回前 n 行(百分比)的数据select top 3 * from first
select top 3 percent * from first
返回合并的多张表的结果集(表的数据类型必须一致)select * from first
union
select * from new_table
条件筛选使用 in 来筛选描述:in 接在 where 子句之后,限定 where 的查询范围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
having 子句对分组结果再选择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)
参考常见的 SQL 语句

我要回帖

更多关于 关于T-SQL语言,下列说法正确的是 的文章

 

随机推荐