问题描述:
   我有三个表
   一个是:t_image.  其中imageId 为主键,belongType,belongId.共3个属性
   一个是  t_travelnote,其中travelNoteId为主键,imageCount.共2个属性。
   一个是:t_message,  其中messageId为主键,imageCount,共2个属性
   其中,根据belongType,和belgongId,可以唯一确定t_travelnote或t_message中的一条记录.
  
   现在,我要使用触发器,当一条记录被插入到t_image中时,我要将对应的t_travelnote或t_message中的imageCount属性加1;
   但是,我要根据,belongType,belongId才能确定,是t_travelnote还是t_message表。
   如下是我写的,触发器:
 begin
        DECLARE t_id int;
DECLARE t_type int;
DECLARE t_bid int;
select max(imageId) into t_id from t_image;
select belongType,belongId into t_type,t_bid from t_image where imageId = t_id;
CASE t_type
       WHEN 0 THEN UPDATE t_travelnote SET imageCount = imageCount+1 WHERE travelNoteId = t_bid;
       WHEN 1 THEN UPDATE t_message SET  imageCount = imageCount+1 WHERE messageId = t_bid;
END CASE;
  end
  我写的应用是多线程的,当使用select max(imageId) into t_id from t_image;就会出现问题。我在网上查询了很多资料,有推荐使用select LAST_INSERT_ID()这个。但是当我把select max(imageId) into t_id from t_image;换成select last_insert_id() into t_id;是触发器就会不起作用。我试过,貌似select last_insert_id() into t_id;只能和插入语句同时使用。
  求教,如果在触发器中获取一个表中最新插入的记录,并且是多线程可以使用的

解决方案 »

  1.   

    1、不要发mysql的东西到sqlserver,不保证所有人都懂,发到mysql对解决你的问题更加有益。
    2、你先别into,看看弹出的select last_insert_id() 能不能出来
    3、即使能出来,貌似并发情况下你这种方法也是有问题,sqlserver可以使用IDENT_CURRENT('数据表名')或者SCOPE_IDENTITY()函数来获取
      

  2.   

    --#1.转到MYSQL专区
    --#2.SQL SERVER使用SCOPE_IDENTITY(),@@identity, ident_current,适合不了有触发器及多线程的情况
      

  3.   

    begin
    DECLARE t_id int;
    DECLARE t_type int;
    DECLARE t_bid int;

    set t_id:= new.imageId;
    set t_type:= new.belongType;
    set t_bid:= new.belongId;
    CASE t_type
    WHEN 0 THEN UPDATE t_travelnote SET imageCount = imageCount+1 WHERE travelNoteId = t_bid;
    WHEN 1 THEN UPDATE t_message SET  imageCount = imageCount+1 WHERE messageId = t_bid;
    END CASE;
    end