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

ed *_*tru 2 sql-server delphi unidac

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

我知道这件事

integerVariable := UniQuery1.RecordCount;
Run Code Online (Sandbox Code Playgroud)

但是这个?

integerVariable := SELECT COUNT(*) FROM Orders WHERE Amount='1000' 
Run Code Online (Sandbox Code Playgroud)

Com*_*sNo 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;
Run Code Online (Sandbox Code Playgroud)

编辑:谢谢你指出"COUNT"将永远有回报.

  • 显然,这个特定的查询将始终返回一个结果,而且,它将返回一个值(而不是NULL),因为`COUNT()`总是返回一个值,永远不会返回NULL.因此,在这种情况下可以省略`not IsEmpty`测试. (4认同)
  • 我不知道`TUniQuery`但是在执行`TUniQuery.Open`之后不是第一行的数据集?像UniQuery1.Open这样的东西是不够的; LCount:= UniQuery1.Fields [0] .AsInteger;`? (2认同)