Sql Server資料庫基本操作
阿新 • • 發佈:2021-01-15
Sql Server資料庫基本操作
已有如下表
其中id列為主鍵,且自動遞增1。在sql語句中是不區分大小寫的。
一、增加
說明:主鍵列是自動增長,在增加插入的時候可以忽略不計。字串需要使用單引號。
insert into PersonInfos
values('1998-9-10','巴拉巴拉','balabala...',10000.99)
如果插入的時候允許為null,也可以插入null。還可以一次性插入多行資料,括號之間使用逗號隔開。
insert into PersonInfos values('1998-9-10','巴拉巴拉','balabala...',10000.99),('9999-9-10','巴拉巴拉啦啦啦','balabala...',null)
二、修改
update PersonInfos
set cnname='張含韻',salary=0
where id=5
上句中修改了id=5的兩列資訊,中間用逗號隔開。where後面的條件語句也可以更復雜,在後的查詢中再細講。
三、刪除
delete from PersonInfos
where id>=4
四、查詢
1、查詢所有列
select * from PersonInfos
使用*代表所有列。
2、查詢指定列
select birthday,cnname from PersonInfos
有多列的時候,中間用逗號隔開。
3、加條件查詢(where)
條件語句where後面支援多種運算子
3.1、比較運算子
支援 =、>、<、<=、>=和!=
select * from PersonInfos
where id>1
select * from PersonInfos
where cnname='張含韻'
3.2、邏輯運算子
支援and、or和not
select * from PersonInfos
where id>2 and birthday>'2000-01-01'
3.3、模糊查詢
like,%表示任意多個任意字元,_表示一個任意字元
select * from PersonInfos where cnname like '張%'
select * from PersonInfos
where cnname like '張__'
3.4、範圍查詢
in表示再一個非連續的範圍內(是這個非連續中的某一個值),not in也是支援的。
select * from PersonInfos
where id in(2,4,6)
select * from PersonInfos
where id not in(1,2,6)
between…and…表示在一個連續的範圍內
select * from PersonInfos
where birthday between '1995-01-01' and '2000-12-30'
3.5、空判斷
select * from PersonInfos
where salary is null
select * from PersonInfos
where salary is not null
4、排序(order by)
asc:升序(ascend)
desc:降序(descend)
select * from PersonInfos
where salary is not null
order by salary desc,birthday asc
5、Top
select top 3 * from PersonInfos
where salary is not null
order by salary desc
薪水前3。
6、聚合函式
6.1、總數
count(*)表示計算總行數,括號中寫星與列名結果是相同的
select count(*) from PersonInfos
where salary is not null
6.2、最大數和最小值
max(列) 表示求此列的最大值
select MAX(salary)
from PersonInfos
where salary is not null
min(列) 表示求此列的最小值
select min(salary)
from PersonInfos
where salary is not null
6.3、求和與平均值
avg(列) 表示求此列的平均值
select avg(salary)
from PersonInfos
where salary is not null
sum(列) 表示求此列的和
select sum(salary)
from PersonInfos
where salary is not null