假设 PayDate
被定义为 date
/datetime
在MSSQL中,您可以使用以下参数:
qryTemp.SQL.Text:=' select top 1 iif(ComeSumm>0,comesumm,0) from cash '
+' where idCashReason=1 and idCashClause=8 and cashNum='+IntToStr(i)
+' and PayDate<:D'
+' order by payDate desc';
qryTemp.Parameters.ParamByName('D').Value := Date;
qryTemp.Parameters.ParamByName('D').DataType := ftDateTime;
我也会改变 cashNum
参数即:
...
+' where idCashReason=1 and idCashClause=8 and cashNum=:cashNum'+
...
qryTemp.Parameters.ParamByName('cashNum').Value := i;
始终更喜欢将兼容的数据类型与您的参数一起使用,而不是格式化和使用字符串。如果您可以明确定义它们,则SQL不需要猜测您的数据类型。
笔记: IIF
是在SQL Server 2012中引入的。用于较旧版本 案子 表达。
在较旧的非固定delphi版本中,参数与Unicode有问题。
所以,如果你 别 使用您可以使用以下参数:
function DateTimeToSqlDateTime(const DT: TDateTime): WideString;
begin
Result := FormatDateTime('yyyy-MM-dd', DT) + ' ' + FormatDateTime('hh:mm:ss', DT);
end;
function SqlDateTimeStr(const DT: TDateTime; const Is_MSSQL: Boolean): WideString;
var
S: WideString;
begin
S := DateTimeToSqlDateTime(DT);
if Is_MSSQL then
Result := Format('CONVERT(DATETIME, ''%s'', 102)', [S])
else
Result := Format('#%s#', [S]); // MS-ACCESS
end;
您的查询看起来如下:
...
+' and PayDate<' + SqlDateTimeStr(Date, True)
...