zoukankan      html  css  js  c++  java
  • postgreSQL建立触发器 trigger

    建立触发器 trigger

    CREATE TRIGGER datenew
      AFTER INSERT OR UPDATE
      ON data
      FOR EACH ROW
      EXECUTE PROCEDURE datatriger();

    触发器函数

     CREATE OR REPLACE FUNCTION datatriger()
        RETURNS trigger AS
    $BODY$
    DECLARE

      gatewayID INTEGER; --数据所属网关ID
       tableExist INTEGER; --表是否存在
       ll INTEGER; --记录条数
       tableName TEXT;  --表名
       pkName TEXT; --主键名称
       query TEXT;
    BEGIN

       SELECT gateway_id INTO gatewayID FROM gateway_conf WHERE gateway_logo=NEW.gateway_logo;
       IF FOUND THEN
          tableName := 'iot_history_'||gatewayID;
          SELECT count(*) INTO tableExist FROM pg_statio_user_tables WHERE relname=tableName;
          -- 如果表不存在则建表
          IF tableExist=0 THEN
           pkName := 'iot_history_pkey_'||gatewayID;
           query := 'CREATE TABLE '||tableName||'

    (
      id serial NOT NULL,
      data_time timestamp without time zone,
      gateway_logo character(50),
      sensor_name integer,
      channel_name integer,
      value numeric(6,2),
      CONSTRAINT '||pkName||' PRIMARY KEY (id )
    )';

           EXECUTE query;    

         query := 'CREATE INDEX idx_his_'||gatewayID||' ON '||tableName||' (id ASC NULLS LAST)';

           EXECUTE query;

       END IF;

      -- 转存数据
        query := 'INSERT INTO '||tableName||' (data_time, gateway_logo, sensor_name, channel_name, value) VALUES ('''||NEW.data_time||''', '''||NEW.gateway_logo||''', '||NEW.sensor_name||', '||NEW.channel_name||', '||NEW.value||')';
        EXECUTE query;

      -- 删除历史数据
        SELECT limits INTO ll FROM gateway_conf WHERE gateway_logo=NEW.gateway_logo;
        IF ll<1000 THEN
           ll := 10000;

       END IF;
        query := 'DELETE FROM '||tableName||' WHERE id < (SELECT MAX(id)-'||ll||' FROM '||tableName||')';
        EXECUTE query;

     END IF;

    return NEW;     
    END;     
    $BODY$
      LANGUAGE plpgsql VOLATILE
      COST 100;
    ALTER FUNCTION datatriger()
      OWNER TO postgres;

  • 相关阅读:
    A Tour of Go Switch
    A Tour of Go Exercise: Fibonacci closure
    curl的简单使用
    thinkphp自动验证方法的使用
    Forbidden You don't have permission to access / on this server. You don't have permission to access /phpmyadmin/ on this server. 解决办法
    创建、删除文件夹和文件夹里的文件
    图片的copy,从一个目录复制到另一个目录
    如何把内容写入到文件
    读取文件操作
    文件打开操作
  • 原文地址:https://www.cnblogs.com/bailuobo/p/2916750.html
Copyright © 2011-2022 走看看