怎样利用SQL查询语言查询数据库中的日期字段?(50分)

Z

zgp

Unregistered / Unconfirmed
GUEST, unregistred user!
假如某数据库中有一字段名为"文件日期“的日期型字段,现在

我要查询数据库中所有文件日期大于1999-1-23的数据。并将SQL

语言保存在另一数据库中,以便今后调用。象这种查询在SQL语句

中增加参数可以很好解决,但参数是死的,一旦脱离原有的运行

环境就会出错。我曾经看到一本书上介绍可按如下办法解决:

select * from Table where 文件日期>|1999-1-23|

但调试出错。我现在有一个我认为很傻的解决办法,就是为数据库

增加三个字符串字段“年”,“月”,“日”。在输入文件日期时

程序自动将日期拆解为年,月,日存储在数据库中。查询时采用

select * from table where (年>1999)and(月>1)and(日>23)

我可真是没辙了,不知各位有何高招,指点指点!
 
给你一下,我刚写并测试过的绝对没有问题。
列出1999-1-1以后的人名和注册日期。
(以大富翁离线数据库为例)
procedure TForm1.BitBtn2Click(Sender: TObject);
begin
query1.sql.clear;
query1.SQL.add('select * from users where regdate > :lastdate');
query1.ParamByName('lastdate').AsDatetime := strtodate('1999-1-1');
query1.open;
query1.first;
while not query1.Eof do
begin
showmessage(query1.fieldbyname('username').asstring
+' '+
query1.fieldbyname('regdate').asstring);
query1.next;
end;
query1.close;
end;

(这50分应该可以到手吧?!)
 
首先我们应该知道paradox的日期型纪录的查询方法,有两种,语句如下:
1、查询具体日期,例如
select * from people.db where birthday>="6/19/1999"
即日期型表示须为月/日/年
2、查询年、月、日之类
select * from people.db where extract(year from birthdate)="1999"
select * from people.db where extract(month from birthdate)="6"

假如你的查询参数是可变的,即日期不固定,那么需要编个函数来件日期转为上文所
说的格式,可以这样:

//转换日期函数
function mydatetostr(indate: tdate): string;
var
year, month, day: word;
begin
decodedate(indate, year, month, day);
result :='"'+ inttostr(month) + '/' + inttostr(day) + '/' +
inttostr(year)+'"';
end;

//获取转换年的函数
function mygetyeartostr(indate: tdate): string;
var
year, month, day: word;
begin
decodedate(indate, year, month, day);
result := inttostr(year);
end;

1、假设要比较的日期由datetimepicker给出,则查询语句可以这样:
with query1 do
begin
close;
sql.Clear;
sql.Add('select * from people.db where birthdate>='+
mydatetostr(datetimepicker1.date));
open;
end;

2、假设要比较的年份由datetimepicker的年份给出,则查询语句可以这样:
with query1 do
begin
close;
sql.Clear;
sql.Add('select * from people.db where
extract(year from birthdate)>='+
mygetyeartostr(datetimepicker1.date));
open;
end;
 
in query's sql property:
select * from yourdb where thedate > :FromDate and thedate < :toDate
set query's params' type to be Date

use following code:
with query1 do
begin
try
close
paramsbyname('fromdate').asdate:= strtodate(edit1.text);
paramsbyname('todate').asdate:= strtodate(edit2.text);
open;
except
// something special....
end;
end;
 
3h与CJ的解答都运用了参数,不能令人满意。

dreamsoft的解答比较好。

SQL 只支持U.S的日期格式(月/日/年),不支持国际日期格式(年-月-日)

因此只需将1999-1-23转换为1/23/1999,查询即可成功。
 
你真是的,实际上,在不同的SQL服务器中有不同做法的麻。
 
顶部