Stored Procedure in MySQL



  • Hallo!

    Kennt sich hier jemand mit STPs unter MySQL aus? Ich habe folgendes Problem:

    create  procedure anzahlberechnen()
        begin
          declare done boolean default false;
          declare anzahl integer;
          declare nextid integer;
          declare upd timestamp;
          declare cur cursor for select id from features;
          declare continue handler for sqlstate '02000' set done=true;
    
          open cur;
    
          while not done do
            fetch cur into nextid;
            if not done then
              set anzahl=(select count(*) from usages where feature_id=nextid);
              set upd=(select max(created_at)  from usages where feature_id=nextid);
              update features set aufrufe=anzahl, updated_at=upd where id=nextid;
            end if;
          end while;
    
          close cur;
        end
    

    Die Selects in Zeile 15 und 16 sind fast identisch. Ich möchte da nur eine Query draus machen.
    Aber wie weise ich dann die beiden Werte des Resultsets meinen Variablen zu? Ich habe folgendes versucht:

    set (anzahl,upd)=(select count(*), max(created_at) from usages where feature_id=nextid);
    

    Das gibt leider einen Syntaxfehler.



  • Ich würde die Query umbauen. Von:

    set anzahl=(select count(*) from usages where feature_id=nextid);
    set upd=(select max(created_at)  from usages where feature_id=nextid);
    update features set aufrufe=anzahl, updated_at=upd where id=nextid;
    

    -->

    update features set 
    aufrufe=(select count(*) from usages where feature_id=nextid),
    updated_at=(select max(created_at) from usages where feature_id=nextid)
    where id=nextid;
    

    Ungetestet. Warum deine Variablenzuweisung nicht funktioniert, kann ich nicht sagen. Stored Procedures mit MySQL sind imo auch nicht so nützlich wie in anderen DBMSen.



  • Danke für den Tipp. Ich hab noch eine andere Möglichkeit gefunden:

    select count(*), max(created_at) into anzahl,upd from usages where feature_id=nextid;
    

    So spart man sich noch ein Select.


Anmelden zum Antworten