How to setup a stored procedure with input parameters using Spring JDBC?

46 views Asked by At

I have a Microsoft SQL Server stored procedure with two parameters:

SP parameters

If there are no errors, the SP returns nothing.

If there's an error, it returns one row with column names Error, ProductID, WarehouseID, ProductCode, WarehouseCode, WarehouseProductID:

Error result

I would like to execute it using Spring JDBC.

I tried this code:

public class AddProductToWarehouseSP extends StoredProcedure {

    public AddProductToWarehouseSP(DataSource ds) {
        setDataSource(ds);
        setFunction(true);
        setSql("spHATAddProductToWarehouse");

        // in parameters
        declareParameter(new SqlParameter("@strProductCode", Types.NVARCHAR));
        declareParameter(new SqlParameter("@strWareHouseCode", Types.NVARCHAR));

        compile();
    }

    public Map<String, Object> execute(String product, String warehouse) {
        return super.execute(product, warehouse);
    }
}

When I execute it with both parameters, I get this result:

Caused by: org.springframework.jdbc.UncategorizedSQLException: CallableStatementCallback; uncategorized SQLException for SQL [{? = call spHATAddProductToWarehouse(?)}]; SQL state [S0004]; error code [201]; Procedure or function 'spHATAddProductToWarehouse' expects parameter '@strWareHouseCode', which was not supplied.; nested exception is com.microsoft.sqlserver.jdbc.SQLServerException: Procedure or function 'spHATAddProductToWarehouse' expects parameter '@strWareHouseCode', which was not supplied.

I tried removing the @ from the parameters @strProductCode and @strWareHouseCode. I'm not sure if it's important, but it doesn't make a difference here.

From the error, it seems that only one parameter is being passed (call spHATAddProductToWarehouse(?)), but I don't understand why.

If I declare the parameters before compiling:

        declareParameter(new SqlOutParameter("Error", Types.NVARCHAR));
        declareParameter(new SqlOutParameter("ProductID", Types.NVARCHAR));
        declareParameter(new SqlOutParameter("WarehouseID", Types.NVARCHAR));
        declareParameter(new SqlOutParameter("ProductCode", Types.NVARCHAR));
        declareParameter(new SqlOutParameter("WarehouseCode", Types.NVARCHAR));
        declareParameter(new SqlOutParameter("WarehouseProductID", Types.NVARCHAR));

I get the following error:

Caused by: org.springframework.jdbc.UncategorizedSQLException: CallableStatementCallback; uncategorized SQLException for SQL [{? = call spHATAddProductToWarehouse(?, ?, ?, ?, ?, ?, ?)}]; SQL state [S0002]; error code [8144]; Procedure or function spHATAddProductToWarehouse has too many arguments specified.; nested exception is com.microsoft.sqlserver.jdbc.SQLServerException: Procedure or function spHATAddProductToWarehouse has too many arguments specified.

How do I set this up properly?

0

There are 0 answers