4

我想知道如何将 SQL 查询结果放入变量中。

我知道这一点

integerVariable := UniQuery1.RecordCount;

但是这个?

integerVariable := SELECT COUNT(*) FROM Orders WHERE Amount='1000' 
4

1 回答 1

7

您需要做的是首先“执行” sql,然后检查结果,如果结果存在,则将其存储在变量中,这就是我的意思:

procedure ...;
var
  LCount: Integer;
begin
  LCount := 0;
  //
  // note that I am doubling the single quote to escape it
  //
  // set the query
  UniQuery1.SQL.Text := 'SELECT COUNT(*) FROM Orders WHERE Amount=''1000'';';
  //
  // "execute" it
  //
  UniQuery1.Open;
  //
  // SELECT COUNT(*) will return 1 record with 1 field
  // most likely the field name is 'count' <= lower case
  // but we are sure that there should be only 1 field so we 
  // access it by Fields[Index].As[TYPE]
  //
  LCount := UniQuery1.Fields[0].AsInteger;
  ShowMessageFmt('Total count of orders with Amount = 1000: %d', [LCount]);
end;

编辑:感谢您指出“COUNT”总会有回报。

于 2012-03-30T14:15:31.910 回答