Sql Server 的crud(增刪改查)以及一些簡單的巢狀查詢
阿新 • • 發佈:2019-01-30
列出一些簡單的查詢語句,做一下筆記!
Ps:使用sql語句最好統一大小寫
1:建立和刪除資料庫
create database dbname //建立資料庫
drop database dbname //刪除資料庫
2:建立表
use dbname //指定要建立表所在的資料庫
create table tbname(
id int not null primary key,
name varchar(50)not null
)
//primary key 主鍵、not null 不為空 、check(a>=600 and b<=800)check約束、as (a列 + b列 + c列) 可指定一列為計算出來的列、unique 唯一約束、foreign key(外來鍵的名稱) references Student(關聯的表的列名) 建立外來鍵
3:增加列或刪除列
alter table 表名 add 列名 varchar(50) //增加列
alter table 表名 drop column 列名 //刪除列
4:刪除表格資料和整個表
drop table <表名> //刪除整個表
delete from <表名> [where條件] //刪除表資料(標識列不會恢復:例如你的標識列到了11那麼用delete 刪除後標識列依舊要重12開始)
truncate table <表名> //刪除表資料)(標識列從新從1 開始)
5:查詢資料
標準查詢:
select * from 表名 //*可以換成特定查詢的列,也可以用as來查詢特定計算列,例如: ABS(數值表示式)絕對值 Celling()進一制, AVG()按列計算平均值SUM 按列計算值的總和 MAX求一列中的最大值 MIN求一列中的最小值 COUNT按列值統計個數
條件查詢:
select * from 表名 where 條件
select distinct * from 表名//去除重複列
select top 10 * form 表名 where 條件 //選取前10條資料
select * from 表名 where datediff('minute' ,f開始時間,getdate())>5
//datediff兩個日期之間的時間差
select name from syscolumns where id=object_id('TableName')//列出列名
排序查詢:
select * from 表名 order by id desc //asc降序
子查詢:
select * from 表名 where id=(select id from table2 where name=abc)
多表連線查詢:
1:內聯接查詢
第一種:直接用where連結查詢
select a.id,b.id,a.name,b.phone from dbo.a,dbo.b where a.id=b.id
第二種:使用inner join
select a.id,b.id,a.name,b.phone from dbo.a inner join dbo.b on a.id=b.id [where 條件]
兩種方式使用起來查詢結果一致
2:外聯接查詢
第一種:左外連結查詢
select a.id,b.id,a.name,b.phone from dbo.a left join dbo.b on a.id=b.id [where 條件]
第一種:右外連結查詢
select a.id,b.id,a.name,b.phone from dbo.a right join dbo.b on a.id=b.id [where 條件]
第三種:完整外聯接查詢
select a.id,b.id,a.name,b.phone from dbo.a full join dbo.b on a.id=b.id [where 條件]
//[where 條件]這個為選加的欄位可以不加條件,完整外聯接為兩表全部查詢出來
模糊查詢:
select * from table1 where name like ’%雲%’
Ps:內聯接與外聯接區別,內聯接查詢時會查詢出兩表匹配的欄位,而外聯接則可以查詢出指定表匹配欄位,另一表若不匹配則為空,實際使用中可能會出現更多的表聯合查詢,原理一致,例:select * from student inner join teacher on student.id=teacher.sid inner join project on student.id=project.sid;
6:增加資料
insert into table1(id,name) values(1,jiajia)
7:修改資料
update table1 set id=5 where 條件範圍
8:刪除資料
delete from table1 where 條件範圍
基礎和常用的就差不多就這些!