Search code examples
mysqldelphidelphi-2007zeos

Using @variables:= in delphi query does not work


I have the following problem.

ZQuery1.SQL.Text:= 
  ' SELECT                                                  '+
  '   IF(q.rank2 = 1, @rank:= 1, @rank:= @rank + 1) AS rank '+
  '   ,q.* FROM (                                            '+
  '   SELECT groep.id - MinGroepId(groep.id) AS rank2       '+
  '     ,groep.otherfields                                  '+
  '   FROM groep                                            '+
  '   ORDER BY rank2 ) q;                                   ';
ZQuery.Open;

When I run this code I get an exception Incorrect token followed by ":" in ZQuery1.
How do I fix this? I need to use Delphi, because I cannot put this select in a MySQL procedure.
Zeos 6 does not support MySQL procedures that return a resultset.

P.S.
I'm using Delphi 2007 and MySQL 5.1 with ZEOS 6.6.6.
Although I'm pretty sure the versions don't matter.
I'm not willing to switch versions as I'm too far into the project.


Solution

  • OK, I hacked a solution.
    But it sure is ugly, still it works (sorta).

    EDIT, this one works in dbForge-MySQL and Delphi

    First I created a stored function 'ranking' in MySQL, that stores a value and/or offset in @rank.

    CREATE DEFINER = 'root'@'localhost'
    FUNCTION MyDatabase.Ranking(NewRank INT, Addition INT)
      RETURNS int(11)
    BEGIN
      IF NOT(NewRank IS NULL) THEN SET @rank:= NewRank; END IF;
      IF NOT(Addition IS NULL) THEN SET @rank:= @rank + Addition; END IF;
      RETURN @rank;   
    END
    

    Next up, I changed the ZQuery1 to read something like:

    select ranking(null,1) as rank
      ,groep.*
      from groep
    join (select ranking(0,null)) r
    

    This works, and the full complex code in Delphi also works.(-_-')
    Another triumph over the evil machines

    So to recap.
    @varname is persistent within a stored procedure (inside a single connection of course).
    Exchanging @varname between the select statement and the stored procedure works in dbForge, but fails in Delphi.