zoukankan      html  css  js  c++  java
  • MySQL实现自动使用uuid作为主键以及解决不能调用触发器的一点思路

    这里使用触发程序实现此功能.

    触发程序语法如下:

    Create trigger <tri_name>

    {before|after}

    {insert|update|delete}

    On <tab_name>

    For each row

    <触发程序SQL语句>

    核心代码:

     1 use t14test
     2 show tables
     3 drop table if exists uuidTest
     4 create table uuidTest(
     5   testId VARCHAR(36) not NULL DEFAULT '1',
     6   testData VARCHAR(32),
     7   PRIMARY KEY(`testId`)
     8 )
     9 /*创建触发器*/
    10 /*
    11  * terminal创建存储过程需要定义分隔符
    12  * delimiter //
    13  * */
    14 create trigger tri_auto_uuid
    15 before insert
    16 on uuidTest
    17 for each ROW
    18 BEGIN
    19 if new.testId = '1' THEN set new.testId = (select uuid());
    20 end if;
    21 END
    22 /*删除触发器*/
    23 drop trigger if exists tri_auto_uuid
    24 /*插入数据*/
    25 insert into uuidTest(testData)VALUES('一条数据') 
    26 select * from uuidTest

    运行了三次插入操作,结果如下:

    使用触发器可实现uuid作为主键.

    有问题的代码:

    1 create trigger tri_auto_uuid
    2 after insert
    3 on uuidTest
    4 for each ROW
    5 update uuidTest set testId=((select uuid()))

    如果这样定义触发程序,看似没问题,也能添加成功,但是录入数据会报错.

    Can't update table 'tb_user' in stored function/trigger because it is already used by statement which invoked this stored function/trigger.

    网上说为了避免递归触发,update一条数据后不能触发对该数据进行除了Set之外的更新操作.否则就会报错.

    可是我这个触发器是after insert 而且是Set 操作,为什么会有问题呢?

    这里存在某种原因,可能和递归触发有关系.暂且不去管他底层是如何运作的.只需要改变一下思路,把after insert 改成 before insert 就行了.

  • 相关阅读:
    ASP.NET编程中非常有用的例子
    打包样式资源
    9.使用类的2个注意点
    面向对象案例
    super必须放到子类this之前
    PHP:根据二维数组中的某个字段进行排序
    Vuex的五个核心属性
    利用按钮控制listview的当前选择项,滚动条跟随动
    c#通过进程名字获取进程路径
    判断客户端是否安装realplayer
  • 原文地址:https://www.cnblogs.com/tomasman/p/7156752.html
Copyright © 2011-2022 走看看