常用的 T-SQL 语言
生活随笔
收集整理的這篇文章主要介紹了
常用的 T-SQL 语言
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
目錄
- 前言
- 變量
- 局部變量的聲明和賦值
- 通配符
- 常用的字符串函數
- substring
- 日期函數
- 轉換數據類型函數
- convert(a,b):強制類型轉換
- 聚合函數
- avg,max,sum,count(*)
- 流程控制語句
- 數據的插入
- 數據的更新
- 數據的刪除
- 數據的查詢
- 去掉重復值
- 返回前 n 行(百分比)的數據
- 返回合并的多張表的結果集(表的數據類型必須一致)
- 條件篩選
- 按照指定序列排序
- 分組
- having 子句對分組結果再選擇
- 連接查詢
- 自連接
- 子查詢(嵌套查詢)
前言
代碼所用表(表名: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]'查詢的結果
常用的字符串函數
substring
select 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_2while
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 > 0select * from new_tablenew_table 表被創建
新表的內容
insert into:從一張表向另一張表(該表已經存在)插入數據
PS:兩張表的屬性類型必須一樣
因為之前插入過數據(在 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 中重復的元素返回前 n 行(百分比)的數據
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 cnamehaving 子句對分組結果再選擇
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)總結
以上是生活随笔為你收集整理的常用的 T-SQL 语言的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: [AHK]--显示器输入源快速切换
- 下一篇: 浅谈RS-485协议