2014-02-07 63 views
0

我有一個存儲過程返回一個ID(SQL Server 2005中):如何返回標識插入存儲過程+ MyBatis的

BEGIN 
    INSERT INTO 
     rolTemplateWeek(rolWeek,employee,date_insert) 
     VALUES(@numberRol,@employeeId,getDate()) 
    Select @id = @@IDENTITY 
END 

Mapper.xml

<insert id="saveRol" parameterType="com.service.specual.dto.RolWeek" statementType="CALLABLE"> 
    { call saveRolWeek(
     #{numberRol,javaType=Integer,jdbcType=INTEGER,mode=IN}, 
     #{employeeId,javaType=Integer,jdbcType=INTEGER,mode=IN}, 
     #{id,javaType=Integer,jdbcType=INTEGER,mode=OUT} 
    )} 
</insert> 

RolWeek.class

public class RolWeek { 

    private int id; 
     private int numberRol; 
    private int employeeId; 
     .... get & setters 

Mapper.java

RolWeek rolWeek= new RolWeek(); 
    rolWeek.setNumberRol(120); 
    rolWeek.setEmployeeId(100); 

    public int saveServiceRolWeek(RolWeek rolWeek); 

插入正常但不返回我的ID,只有「1」¿如何返回我插入的ID?

回答

1
-- 
-- Use output clause, make sure id is OUTPUT 
-- 

CREATE PROCEDURE saveRolWeek 
    @numberRol INT, 
    @employeeId INT, 
    @id INT OUTPUT 
AS 
BEGIN 

    SELECT @id = 
     INSERT INTO rolTemplateWeek(rolWeek, employee, date_insert) 
     OUTPUT INSERTED.ID 
     VALUES(@numberRol, @employeeId, getDate()); 
END 

-- Sample call with 1, 1 as parameters 
DECLARE @retid int = null; 
EXECUTE dbo.saveRolWeek 1, 1, @retid = @id OUTPUT; 
+0

謝謝,是的我的Id是輸出。當我嘗試用你的coude修改我的存儲過程向我顯示插入錯誤:「OUTPUT INSERTED.ID」這個語句必須在中間? – vljc2004