Delphi TADOQuery选择前N名

时间:2015-01-29 16:55:12

标签: delphi tadoquery

我正在尝试仅选择TADOQuery中的顶级 N 项,但是当我激活查询时它会给我和错误。它似乎找到了top参数就好了,但在执行时无法替换它。如果我没有用" Top N"来限制SQ​​L语句。代码工作正常。

以下是代码的基本概念。

const SQL_STR = 'SELECT TOP :cnt name from dSomeTable where done = FALSE';

var
  dbCon         : TADOConnection;
  toSolveQry    : TADOQuery;
  getCnt        : TParameter;
  names         : TField;
  threadCnt     : Integer;

begin
  threadCnt  := 3;
  dbCon := TADOConnection.Create(nil);
  ...
  dbCon.Open();

  toSolveQry := TADOQuery.Create(nil);
  toSolveQry.Connection := dbCon;
  toSolveQry.SQL.Add(SQL_STR);
  toSolveQry.ParamCheck := True;
  getCnt := toSolveQry.Parameters.ParamByName('cnt');
  getCnt.Value := threadCnt;

  toSolveQry.Active := true; //Error here

  names       := toSolveQry.FieldByName('name');
  ...
end

1 个答案:

答案 0 :(得分:4)

参数不能用于SELECTWHERE子句中的列名。这也排除了TOP x中的使用。

改为使用Format功能:

const SQL_STR = 'SELECT TOP %d name from dSomeTable where done = FALSE';

toSolveQry.SQL.Text := Format(SQL_STR, [threadCnt]);
toSolveQry.Open;

使用整数格式说明符(%d)可以防止SQL注入,因为如果你提供的除了整数值之外的任何东西作为Format的参数,Delphi将引发异常。