資料庫的查詢 SQL Server

2021-10-03 10:57:31 字數 2370 閱讀 7059

1、為表起別名as

select

*from classinfo as ui

查詢全部列、指定列

為列起別名as

select ui.cid from classinfo ui
2、查詢前n部分資料:

top n 列名:表示檢視前n行

select

top3

*from classinfo--查詢前三行所有列

top n percent 列名:表示檢視前百分之幾的資料

select

top5

percent

*from classinfo--查詢前百分之五的所有列資料

3、排序:order by 列名1 asc(公升序)|desc(降序),列名1 asc|desc…

select

*from userinfo

order

by cid desc

,cname desc

--先根據cis降序排,再根據cname公升序排

4、消除重複行:distinct

select

distinct cname from classinfo--消除classinfo裡的cname相同的(只是查詢時消除,並不是刪除資料庫裡的)

5、條件查詢:寫在where後面

對行進行篩選,返回bool型別的值,如果某行中的列資料滿足條件,則加入結果集,否則不出現在結果集中

比較運算子:=,>,>=,<,<=,!=或<>

select

*from classinfo

where cid>

3

between ... and ...表示在乙個連續的範圍內
select

*from classinfo

where cid between

2and

4

in表示在乙個非連續的範圍內
select

*from classinfo

where cid in(3

,5)

邏輯運算子:and,or,not
select

*from classinfo

where cid=

3or cid=

5select

*from classinfo

where

not cid>=

2and cid<=

5

6、模糊查詢

用於處理字串型別的值,運算子包括:like % _ ^

%若干個

select

*from studentinfo

where sphone like

'%4%'

--**號中含4

_單個

select

*from studentinfo

where sname like

'虎_'

--虎某某

範圍

在表示乙個連續的範圍可以使用-

select

*from studentinfo

where sphone like

'1[3-5]%'

--**號1開頭第二個數字時3到5範圍內的**號

%與_寫在中表示本身的含義

^寫在內部的開頭,表示不使用內部的任何字元

select

*from studentinfo

where sphone like

'1[^553]%'

--**號1開頭接著非553內的**號

7、null的判斷:使用is null或is not null,與其它值計算時返回null,排序時null被認為是最小

select

*from studentinfo

where sphone is

null

--查詢**是空的

SQL Server資料庫查詢

開啟我們的sql server資料庫,找到要查詢的資料庫表,右鍵單擊然後選擇新建查詢,select 選擇我們要查詢的表sys academe學院表 聯合 sys class.classname班級表的班級名稱和sys grade.gradename年級表的年級編號來查詢出資料。下面是查詢的 sele...

SQL Server 跨資料庫查詢

語句 select from 資料庫a.dbo.表a a,資料庫b.dbo.表b b where a.field b.field dbo 可以省略 如 select from 資料庫a.表a a,資料庫b.表b b where a.field b.field sqlserver資料庫 這句是對映乙個...

查詢SQL SERVER 資料庫版本

select substring cast serverproperty productversion as nvarchar 128 1,charindex cast serverproperty productversion as nvarchar 128 1 1 8 對應 sql server...