• sql 基础--触发器,如何限制表最大行数


    参考:http://blog.csdn.net/love_android_2011/article/details/20137385

    http://blog.csdn.net/lihuibo128/article/details/43667865

    语法

    创建触发器的基本语法如下:

    CREATE  TRIGGER trigger_name [BEFORE|AFTER] event_name 
    ON table_name
    BEGIN
     -- Trigger logic goes here....
    END;

    在这里,event_name 可能是INSERT,DELETE和UPDATE操作所提到的表table_name数据库。您可以选择指定FOR EACH ROW表名后。

    以下是语法上创建一个触发器UPDATE操作一个或多个指定一个表列如下:

    CREATE  TRIGGER trigger_name [BEFORE|AFTER] UPDATE OF column_name 
    ON table_name
    BEGIN
     -- Trigger logic goes here....
    END;


    例子:
    CREATE TRIGGER delete_till_50 INSERT ON _table WHEN (select count(*) from _table)>50 
    BEGIN
        DELETE FROM _table WHERE _table._id IN  (SELECT _table._id FROM _table ORDER BY _table._id limit (select count(*) -50 from _table ));
    END;
    

      注意:1.默认是 BEFORE,即在插入时判断执行 左右最终表会有51条数据

         2.BEGIN 要与前后与空格

    所以用ormlite 语句改写为:

        // 初次运行程序会执行该onCreate方法,如果不是初次运行程序则不会执行该方法,防止重复建表。
        @Override
        public void onCreate(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource) {
            try {
                //创建表
                TableUtils.createTable(connectionSource, CommentMessageItemBean.class);
    
                //设置触发器限制表条数上限
    
                String _table = "tb_comment_message_item";
                String _maxrow = 1000 + "";
    
                String deleteTrigger = "CREATE TRIGGER delete_till AFTER INSERT ON " + _table + " WHEN (select count(*) from " + _table + ")>" + _maxrow + " " +
                        "BEGIN " +
                        "DELETE FROM " + _table + " WHERE " + _table + ".id IN  (SELECT " + _table + ".id FROM " + _table + " ORDER BY " + _table + ".id limit (select count(*) -"+_maxrow+" from " + _table + " ));" +" "+
                        "END;";
    
                sqLiteDatabase.execSQL(deleteTrigger);
    
            } catch (SQLException e) {
                e.printStackTrace();
            }
    
        }
    1             String deleteTrigger = "CREATE TRIGGER delete_till AFTER INSERT ON " + _table + " WHEN (select count(*) from " + _table + ")>" + _maxrow + " " +
    2                     "BEGIN " +
    3                     "DELETE FROM " + _table + " WHERE " + _table + ".id IN  (SELECT " + _table + ".id FROM " + _table + " ORDER BY " + _table + ".id limit (select count(*) -"+_maxrow+" from " + _table + " ));" +" "+
    4                     "END;";




  • 相关阅读:
    CCNA 第二章 以太网回顾
    CCNA 第一章 网络互联
    solidworks中 toolbox调用出现未配置的解决方法
    linux之df命令
    linux之du命令
    linux之pid文件
    linux之mysql启动问题
    linux之使用cron,logrotate管理日志文件
    wordpress(一)wordpress环境的搭建
    phpwind8.7升级9.0.1过程(四)20130207升级到20141228
  • 原文地址:https://www.cnblogs.com/wjw334/p/6490156.html
Copyright © 2020-2023  润新知