常用SQL查詢指令碼

2021-03-31 13:11:00 字數 2480 閱讀 3901

本文假定讀者已經對資料庫連線技術有所了解,因此只討論有關sql查詢命令的語法。

表結構如下(ms access 2000):

表名:usertable

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

欄位名         字段型別

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

userid      自動計數(長整型)

username      文字

user***       文字

createdate    日期/時間(預設值為now())

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

一、用select命令提取記錄

1、取得表中所有記錄

select命令,語句如下:

"select *from usertable"

2、取得表中userid欄位記錄

"select userid from usertable"

3、取得表中userid、user***字段記錄

"select userid, user*** from usertable"

4、取得表中user***值為「男」的記錄

"select from usertable where user*** = '男'"

5、取得表中username值中包含「張」字的記錄

"select from usertable where username like '%男%'"

6、取得表中所有記錄,按createdate字段值降序排列

"select from usertable order by createdate desc"

說明:

1)、以上命令可以組合使用,如,取得表中username中包含「浩」字的,userid的值,並按createdate值的時間降序排列,那麼命令如下:

"select userid from usertable where username like '%浩%' order by createdate desc"

2)、使用中應注意,如果字段型別為文字,則在條件判別時,應在條件字外加上單引號,此規則適用於任何乙個sql查詢命令。

3)、條件字中的「%」為萬用字元。

4)、當判別條件多於一條時,應以「and」或「or」連線。

二、用insert into命令插入新記錄

1、插入一條新記錄

"insert into usertable (username, user***) values ('張浩南', '男')"

說明:

這裡需要注意的是,插入的記錄的值的型別應符合表中的字段型別,否則會出錯。其實使用單引號只是個便捷的方法,但並不規範,因為如果要插入的記錄中本身含有單引號,則會出現錯誤(雖然這種情況並不經常發生,但有可能存在)。所以我們最好使用乙個自定義的函式來實現單引號的替換。方法如下

function sqlstr(data)

sqlstr="'" & replace(data, "'", "''") & "'"

end function

在命令中則為:

dim name, ***

name="張浩南"

***="男"

"insert into usertable (username, user***) values (" & sqlstr(name) & ", " & sqlstr(***) & ")"

這樣則無論值中是否含有單引號或雙引號均不會出錯。

但請注意,這個規則只適用於型別為文字的字段,如果為其它型別,則一般無需考慮,即不必加任何符號。

三、用update更新記錄

1、更新全部記錄的全部字段

"update usertable set userid=1, user***='男', username='徐勇', createdate=" & cdate(createdate)

說明:

式中的值可以用運算表示式,如:userid=userid+1等。

2、更新username字段值為「徐勇」的記錄值

"update usertable set userid=1, username='徐詠' where username='徐勇'"

說明:

需要組合條件查詢時,方法同select。另外此處也要注意單引號問題。

四、用delete刪除記錄

1、刪除全部記錄

"delete from usertable"

2、刪除特定條件的記錄,如刪除userid為「20」的記錄

"delete from usertable where userid=20"

3、刪除組合條件記錄,如刪除user***為「女」,username中包含「張」的記錄

"delete from usertable where user***='女' and username like '%張%'"

說明:

注意單引號問題。

SQL 常用指令碼

select o.name as tablename,c.name as colname,k.keyno as sort from sysindexes i join sysindexkeys k on i.id k.id and i.indid k.indid join sysobjects o ...

MySQL常用SQL指令碼

1.重新定義表中某個欄位的屬性 alter table user modify column name varchar 200 comment 姓名 2.給表新增列欄位 alter table user add column varchar 200 comment 性別 3.刪除表中的乙個列欄位 a...

常用 SQL指令碼 收集

declare ttable 成績 int,學生 varchar 10 insert tselect 100,小張 union select 70 小力 union select 80 小剛 union select 78 小王 select pid select count 1 from twhe...