sql_procedures.sql 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. DROP PROCEDURE IF EXISTS insert_topic;
  2. DELIMITER //
  3. CREATE PROCEDURE insert_topic(vtopic varchar(64),newid smallint unsigned)
  4. begin
  5. declare tpos tinyint;
  6. declare feldname varchar(64);
  7. DECLARE bcfgDone INT;
  8. DECLARE cfg_curs CURSOR FOR SELECT cfg_topic.feld,cfg_topic.pos FROM cfg_topic where cfg_topic.minlength is null or cfg_topic.minlength <= (select (length(vtopic) - length(replace(vtopic,'/','')) +1));
  9. DECLARE CONTINUE HANDLER FOR NOT FOUND SET bcfgDone = 1;
  10. OPEN cfg_curs;
  11. REPEAT
  12. fetch cfg_curs into feldname,tpos;
  13. if (tpos < 0) then
  14. select substring_index(substring_index(vtopic,'/',tpos),'/',1) into @feldinhalt;
  15. else
  16. select substring_index(substring_index(vtopic,'/',tpos),'/',-1) into @feldinhalt;
  17. end if;
  18. if (select count(*) from topic where topic.tid = newid and topic.feld=feldname) = 0 then
  19. insert into topic (tid,feld,inhalt) values (newid,feldname,@feldinhalt);
  20. end if;
  21. UNTIL bcfgDone END REPEAT;
  22. close cfg_curs;
  23. end
  24. //
  25. DELIMITER ;
  26. DROP PROCEDURE IF EXISTS import_data;
  27. DELIMITER //
  28. CREATE PROCEDURE import_data()
  29. BEGIN
  30. DECLARE bDone INT;
  31. DECLARE vtopic VARCHAR(64); -- or approriate type
  32. DECLARE curs CURSOR FOR SELECT DISTINCT topic FROM datatmp;
  33. DECLARE CONTINUE HANDLER FOR NOT FOUND SET bDone = 1;
  34. OPEN curs;
  35. SET bDone = 0;
  36. SELECT if(max(tid) is null,1,max(tid)+1) into @newid from topic;
  37. SELECT @newid;
  38. REPEAT
  39. FETCH curs INTO vtopic;
  40. select vtopic;
  41. IF (select max(topic.tid) from topic where feld = 'topic' and inhalt = vtopic) is null THEN
  42. call insert_topic(vtopic,@newid);
  43. INSERT INTO topic (tid,feld,inhalt) VALUES (@newid,'topic',vtopic);
  44. select @newid+1 into @newid;
  45. ELSE
  46. select max(topic.tid) into @actid from topic where feld='topic' and inhalt = vtopic;
  47. END IF;
  48. COMMIT;
  49. insert into data_storage (time,sensortime,tid,value) select tmp.time,tmp.sensortime,@actid as tid,tmp.value from datatmp tmp where tmp.topic=vtopic;
  50. COMMIT;
  51. select @actid;
  52. UNTIL bDone END REPEAT;
  53. CLOSE curs;
  54. END
  55. //
  56. DELIMITER ;
  57. DROP PROCEDURE IF EXISTS imd;
  58. DELIMITER //
  59. CREATE PROCEDURE imd()
  60. BEGIN
  61. create table datatmp as select * from datain;
  62. call import_data();
  63. delete from datain where datain.time <= (select max(dt.time) from datatmp dt);
  64. drop table datatmp;
  65. END
  66. //
  67. DELIMITER ;
  68. CREATE EVENT import_data ON SCHEDULE EVERY 1 MINUTE DO CALL imd();