Delphi查询Sqlserver数据库传入日期类型方法总结

很常见的一个问题要查询数据库中某个时间段的记录?在写sql语句时查询肯定要传入开始结束时间参数,翻阅程序工程代码发现不同人写法不同,仔细想想其实写sql查询语句传入日期时间参数是比传入整形或字符串类型要复杂些,因为设计到日期时间的现实格式,把常见的几种写法总结如下:

  1. 最普通最麻烦的写法,sql语句直接用+连接来写:比如Delphi中直接传入TdateTime类型的参数StartTime、StopTime方法如下:

    SQL.Add(' and (a.begin_time BETWEEN CONVERT(DATETIME, ''' + FormatDateTime('yyyy-mm-dd hh:nn:ss', StartTime) + ''', 102) ');

    SQL.Add(' and CONVERT(DATETIME, ''' + FormatDateTime('yyyy-mm-dd hh:nn:ss', StopTime) + ''', 102))');

    Delphi中直接传入string类型的格式为yyyymmdd类型的日期参数写法如下:

SQL.Add(' and convert(int,(convert(varchar,inquestinfo.begin_time,112)))<= ' + EndDate);

SQL.Add(' and convert(int,(convert(varchar,inquestinfo.end_time,112)))>= ' + BeginDate);

这种写法要熟悉sqlserver中函数convert的用法,还要知道最后一个参数值对应的整数值的格式,很麻烦也浪费时间。

  1. 声明sql变量的写法

    qry.SQL.Add('declare @begin_time datetime');

    qry.SQL.Add('declare @stop_time datetime');

    qry.SQL.Add('declare @inquest_serial int');

    qry.SQL.Add('set @begin_time = CONVERT(DATETIME, ''' + FormatDateTime('yyyy-mm-dd hh:nn:ss', BegTime) + ''', 102)');

    qry.SQL.Add('set @stop_time = CONVERT(DATETIME, ''' + FormatDateTime('yyyy-mm-dd hh:nn:ss', EndTime) + ''', 102)');

    这种方法给变量赋值还是要用到CONVERT函数,绕个玩麻烦。

  2. 最简单最省时的写法,参数化SQL法

    SQL.Add(' and begin_time < :endTime and end_time > :beginTime');

    Parameters.ParamByName('endTime').Value := EndTime;

    Parameters.ParamByName('beginTime').Value := BeginTime;

    此法简单省时,还可以避免SQL注入等安全问题,充分利用了系统封装的便利高效性。不过要注意:动态加入tadoquery.sql的参数化SQL语句在调用参数前先解析下SQL,如下: Parameters.ParseSQL(SQL.Text, True);

代码例下:

with self.qry do begin

try

SQL.Clear();

Parameters.Clear();

Close();

Prepared := False;

SQL.Text := 'SELECT [CurrentNO], [Mask], [CurrentDate] FROM [CurrentID]' +

' WHERE [TabName]= :TabName AND [KeyField]=:KeyField;';

Parameters.ParseSQL(SQL.Text, True); //一定要加,否则运行时报告异常edatabaseerror parameter 'table' not found,就是说参数table在SQL中找不到

Parameters.ParamByName('TabName').Value := Table;

Parameters.ParamByName('KeyField').Value := KeyField;

Prepared := True;

Open();