Page 1 of 1

Issue with AsBoolean casting & UNION

Posted: Mon 14 Mar 2011 19:17
by maciejmt
Delphi XE & MyDAC 6

Code: Select all

CREATE TABLE `tab` (
  `id` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
  `a` BOOLEAN NOT NULL,
  PRIMARY KEY (`id`)
)
ENGINE = InnoDB;


insert into tab(a) values('1');
insert into tab(a) values('1');
insert into tab(a) values('0');
insert into tab(a) values('1');
insert into tab(a) values('0');
insert into tab(a) values('0');
insert into tab(a) values('0');
With UNION statement, AsBoolean causing exeception.

Code: Select all

procedure TForm1.Button1Click(Sender: TObject);
var
  B: Boolean;
begin
  myquery1.SQL.Text := 'select a from tab WHERE a=0 UNION select a from tab WHERE a=1';
  myquery1.Open;
  while not myquery1.Eof do
  begin
    B := myquery1.Fields[0].AsBoolean;

    myquery1.Next;
  end;
  myquery1.Close;
end;

Posted: Tue 15 Mar 2011 09:05
by AndreyZ
Hello,

For TINYINT(1) fields MySQL server returns boolean types for simple queries and smallint types for queries with UNION. In the second case we cannot determine whether the field is boolean or not. To avoid this problem, you can use the following code:

Code: Select all

B := Boolean(myquery1.Fields[0].AsInteger);

Posted: Tue 15 Mar 2011 11:03
by maciejmt
I know, but I need universal solution (I use Union and not union query).

In this case an exception is rising.

Code: Select all

procedure TForm1.Button1Click(Sender: TObject);
var
  I:Integer;
begin
  myquery1.SQL.Text := 'select a from tab';
  myquery1.Open;
  I := myquery1.Fields[0].AsInteger;
  myquery1.Close;
end;

Instead of try except construction, the only good solution is:

Code: Select all

if Pos('UNION', myquery1.sql.text) > 0 then
B := Boolean(MyQuery1.Fields[0].AsInteger)
else
B := MyQuery1.Fields[0].AsBoolean;
?

Posted: Wed 16 Mar 2011 08:19
by AndreyZ
To solve the problem, you should set the TMyQuery.Options.EnableBoolean option to False. This option is used to specify the method of representation of the TINYINT(1) fields. In this case you can use the myquery1.Fields[0].AsInteger property for both SQL queries (with and without UNION).