天天看點

SQL文法幫助

假設student表中存儲着學生的考試成績,資料資訊如下:

ID

Name

Type

Score

PassDate

1

張三

數學

90

2008-09-01

2

李四

國文

93

2007-12-02

3

王五

化學

70

2008-01-10

其中,各列的資料類型如下:

ID  NUMBER  數字類型

Name  VARCHAR2  字元串類型

Type  VARCHAR2  字元串類型

Score  NUMBER  數字類型

PassDate  DATE  日期類型

-----------------------------------------------------------------------------------------

對于數字類型列,可使用的比較符有:=、!=、>、<、>=、<=、between...and...、in、not in

例, 執行以下SQL語句進行查詢:

1. select * from student where score = 93

查詢結果:

2. select * from student where score >= 90

3. select * from student where score between 90 and 100

對于字元串類型列,在查詢時需要在字元串兩邊添加單引号('),可使用的比較符有:=、!=、like、in、not like、not in

1. select * from student where name = '李四'

2. 當不确定字元串内容時,可使用like進行查詢,其中(%)意為占位符。

select * from student where type like '%數%'

3. 當需要同時查詢多個字元串時,可使用in進行查詢,其中每個字元串需用(,)隔開。

select * from student where type in ('國文', '化學')

對于日期類型列,在查詢時也需要在日期兩邊添加單引号('),并且日期格式寫法為:01-AUG-08,即2008-08-01(英文簡寫不區分大小寫)。

可使用的比較符有:=、!=、>、<、>=、<=、between ... and ...、like、in、not like、not in

1. select * from student where passdate <= '1-aug-08'

2. 下例通過not與like組合使用,查詢日期為07年的資料。

select * from student where passdate not like '%08%'

3. 當需要查詢某個時間段時,可使用between ... and ...進行查詢。

select * from student where passdate between '01-Jan-07' and '01-May-08'

在查詢過程中,可能會需要輸入多個查詢條件,這時可使用and、or進行多條件組合。

1. 下例将查詢國文考試成績在90分以上的同學,需要使用and符。

select * from student where type = '國文' and score >= 90

2. 下例将查詢考試成績在90分以上或60分以下的同學,需要使用or符。

select * from student where score > 90 or score < 60

注意:以上藍色SQL文法均要使用英文半角!

<b></b>

<b>本文轉自Gnie部落格園部落格,原文連結:http://www.cnblogs.com/gnielee/archive/2008/10/24/tsql-query.html,如需轉載請自行聯系原作者</b>