SQL查询输出到Delphi中的变量?

时间:2012-03-30 14:03:40

标签: sql-server delphi unidac

我想知道如何将SQL Query结果放入变量。

我知道这个

integerVariable := UniQuery1.RecordCount;

但是这个?

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

1 个答案:

答案 0 :(得分:6)

你需要做的是首先“执行”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”总会有回报。