access中使用sql語句應(yīng)注意的地方及幾點(diǎn)技巧
引用:fred
以下sql語句在access xp的查詢中測試通過
建表:
create table tab1 (
id counter,
name string,
age integer,
[date] datetime);
技巧:
自增字段用 counter 聲明.
字段名為關(guān)鍵字的字段用方括號[]括起來,數(shù)字作為字段名也可行.
建立索引:
下面的語句在tab1的date列上建立可重復(fù)索引
create index idate on tab1 ([date]);
完成后access中字段date索引屬性顯示為 - 有(有重復(fù)).
下面的語句在tab1的name列上建立不可重復(fù)索引
create unique index iname on tab1 (name);
完成后access中字段name索引屬性顯示為 - 有(無重復(fù)).
下面的語句刪除剛才建立的兩個(gè)索引
drop index idate on tab1;
drop index iname on tab1;
access與sqlserver中的update語句對比:
sqlserver中更新多表的update語句:
update tab1
set a.name = b.name
from tab1 a,tab2 b
where a.id = b.id;
同樣功能的sql語句在access中應(yīng)該是
update tab1 a,tab2 b
set a.name = b.name
where a.id = b.id;
即:access中的update語句沒有from子句,所有引用的表都列在update關(guān)鍵字后.
上例中如果tab2可以不是一個(gè)表,而是一個(gè)查詢,例:
update tab1 a,(select id,name from tab2) b
set a.name = b.name
where a.id = b.id;
訪問多個(gè)不同的access數(shù)據(jù)庫-在sql中使用in子句:
select a.*,b.* from tab1 a,tab2 b in 'db2.mdb' where a.id=b.id;
上面的sql語句查詢出當(dāng)前數(shù)據(jù)庫中tab1和db2.mdb(當(dāng)前文件夾中)中tab2以id為關(guān)聯(lián)的所有記錄.
缺點(diǎn)-外部數(shù)據(jù)庫不能帶密碼.
補(bǔ)充:看到ugvanxk在一貼中的答復(fù),可以用
select * from [c:/aa/a.mdb;pwd=1111].table1;
access xp測試通過
在access中訪問其它odbc數(shù)據(jù)源
下例在access中查詢sqlserver中的數(shù)據(jù)
select * from tab1 in [odbc]
[odbc;driver=sql server;uid=sa;pwd=;server=127.0.0.1;database=demo;]
外部數(shù)據(jù)源連接屬性的完整參數(shù)是:
[odbc;driver=driver;server=server;database=database;uid=user;pwd=password;]
其中的driver=driver可以在注冊表中的
hkey_local_machine oftware/odbc/odbcinst.ini/
中找到
access支持子查詢
access支持外連接,但不包括完整外部聯(lián)接,如支持
left join 或 right join
但不支持
full outer join 或 full join
access中的日期查詢
注意:access中的日期時(shí)間分隔符是#而不是引號
select * from tab1 where [date]>#2002-1-1#;
在delphi中我這樣用
sql.add(format(
'select * from tab1 where [date]>#%s#;',
[datetostr(date)]));
access中的字符串可以用雙引號分隔,但sqlserver不認(rèn),所以為了遷移方便和兼容,
建議用單引號作為字符串分隔符.
access的約束
在jet sql參考中關(guān)于約束的內(nèi)容不夠詳細(xì),可以參考sql server的聯(lián)機(jī)叢書
下面的sql為a表的name字段增加非空約束
alter table a add constraint a_checkname check (not [name] is null)
注意:每一個(gè)約束都是一個(gè)對象,都有一個(gè)名字
下面的語句把id列設(shè)置為主鍵
alter table [表] add primary key (id)
下面的語句把id列改為自動編號類型,并且設(shè)置為主鍵
alter table [表] alter [id] counter constraint [表_p] primary key
添加復(fù)合主鍵
下面的sql為tb_demo表添加復(fù)合主鍵(id,id2).
alter table tb_demo
add constraint tb_demo_pk
primary key (id,id2)
,歡迎訪問網(wǎng)頁設(shè)計(jì)愛好者web開發(fā)。