0

我需要在存储过程中创建一条新记录并返回插入记录的 ID。我敢肯定这很简单,但我不知道正确的方法......

我创建了一个简单的存储过程,它需要 3 个参数,插入一条记录并返回插入记录的值:

ALTER PROCEDURE [dbo].[BronzeLabsCreateServiceEquipment]
    @companyID int = null,
    @manufacturerID int = null,
    @modelID int = null,
    @serialNumber varchar(255) = '',
    @machine varchar(255) = '',
    @location varchar(255) = ''
AS
BEGIN
    SET NOCOUNT ON;

    INSERT INTO ServiceEquipment(CompanyID, ManufacturerID, ModelID, SerialNumber, Machine, Location)
    VALUES (@companyID, @manufacturerID, @modelID, @serialNumber, @machine, @location)

    Declare @new_identity int;
    SELECT @new_identity = SCOPE_IDENTITY()
    return @new_identity

END

然后我尝试用Java调用它

String queryStringAlt = "CALL dbo.BronzeLabsCreateServiceEquipment(?, ?, ?, ?, ?, ?)";
CallableStatement cs = conn.prepareCall(queryStringAlt); 

    cs.setString(1, null);
    cs.setString(2, null);
    cs.setString(3, null);
    cs.setString(4, "new123-1");
    cs.setString(5, "new123-2");
    cs.setString(6, "new123-3");

ResultSet rs = cs.executeQuery();

...但是准备好的语句不返回结果集,因此最后一行不起作用。它返回什么,我如何获得它?还是我在这里做错了 - 我应该使用输出参数(我尝试过但有一个语法问题我无法深入了解)。

4

1 回答 1

0

谢谢你的帮助。我没有想过将身份放入结果集中,所以新代码是:

存储过程

ALTER PROCEDURE [dbo].[BronzeLabsCreateServiceEquipment]
    @companyID int = null,
    @manufacturerID int = null,
    @modelID int = null,
    @serialNumber varchar(255) = '',
    @machine varchar(255) = '',
    @location varchar(255) = ''
AS
BEGIN
    SET NOCOUNT ON;

    INSERT INTO ServiceEquipment(CompanyID, ManufacturerID, ModelID, SerialNumber, Machine, Location)
    VALUES (@companyID, @manufacturerID, @modelID, @serialNumber, @machine, @location)

    SELECT SCOPE_IDENTITY() AS equipmentID

END

Java 代码

String queryStringAlt = "CALL dbo.BronzeLabsCreateServiceEquipment(?, ?, ?, ?, ?, ?)";
CallableStatement cs = conn.prepareCall(queryStringAlt); 

    cs.setString(1, null);
    cs.setString(2, null);
    cs.setString(3, null);
    cs.setString(4, "new123-1");
    cs.setString(5, "new123-2");
    cs.setString(6, "new123-3");

ResultSet rs = cs.executeQuery();
if(rs.next()) {
    System.out.println("Equipment ID: " + rs.getString("equipmentID"));
}
于 2013-09-18T11:06:20.617 回答