Search code examples
mybatisidentity-column

@@identity immediate use


Say I have this MYBATIS statement:

<insert id="insertValue" resultType="car" > 
   BEGIN TRANSACTION
      INSERT INTO table1 ( somefield,... ) VALUES ( #{value},... ); 

      <selectKey keyProperty="carId" resultClass="int"> 
         SELECT @@IDENTITY as carId 
      </selectKey>

      UPDATE table2
      set fieldx = #{carId}
      where table2Id = 500;
   COMMIT
</insert>

I am getting value 0 for carId, should be the key to the just added record into table1

How do I grab the recently generated keyValue for immediate use?


Solution

  • I think what you want to do is :

    insert table1 ......
    declare @var int
    set @var= scope_identity()
    update table2 set ... where id = @var