我需要在存储过程中创建一个新记录并返回插入记录的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();
...但是,准备好的语句不会返回结果集,以便最后一行不起作用。它返回什么,我如何得到它?或者我在这里做错了 - 我应该使用输出参数(我尝试但是有一个语法问题我无法触及底部)。
答案 0 :(得分: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
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"));
}