4

I Would like to know how Can I put the SQL Query result into a variable.

I'm aware of this

integerVariable := UniQuery1.RecordCount;

but this?

integerVariable := SELECT COUNT(*) FROM Orders WHERE Amount='1000' 
3
  • 3
    Ehm, what ? I think you mean something like UniQuery1.Fields[0].AsInteger if you are on the first row of your dataset, but we don't even know what type is the UniQuery1. Commented Mar 30, 2012 at 14:11
  • 1
    @TLama UniQuery1: TUniQuery, s/he uses the UniDAC components from devart.com/unidac Commented Mar 30, 2012 at 14:17
  • 1
    Don't forget to accept the answers that resolve your questions this way. It will help the future visitors to recognize the right solution. Thanks and enjoy StackOverflow! Commented Mar 31, 2012 at 0:26

1 Answer 1

7

what you need to do is first "execute" the sql, then check for result, if result is present, then store it in a variable, here's what I mean:

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;

EDIT: thank you for point out that "COUNT" will always have a return.

Sign up to request clarification or add additional context in comments.

6 Comments

Obviously, this particular query will always return a result, moreover, it will return a value (as opposed to NULL), because COUNT() always returns a value, never a NULL. So, the not IsEmpty test can be omitted in this case.
@Andriy is right. the UniQuery1.FindFirst is also not needed.
I don't know TUniQuery but isn't the dataset already on the first row after performing TUniQuery.Open ? Wouldn't be enough something like UniQuery1.Open; LCount := UniQuery1.Fields[0].AsInteger; ?
The field name is not count. to specify a name use select count(*) as as RecordCount and use UniQuery1.FiledByName('RecordCount').AsInteger. also better to use Parameters in your SQL.Text instead of doubling the single quote.
@kobik I wrote "most likely the field name is 'count'", in Postgres the field name would be "count" if no alias defined, don't know about sql server
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.