Passing a user-defined table type to a SQL Server stored procedure using JDBC

前端 未结 2 465
星月不相逢
星月不相逢 2020-12-06 22:11

We\'ve got this User-Defined-Table Type in SQL Server:

CREATE TYPE [dbo].[INITVALS_MSG] AS TABLE(
    [SDate] [decimal](8, 0) NOT NULL,
    [EDate] [decimal]         


        
相关标签:
2条回答
  • 2020-12-06 22:30

    Yes, it is now possible. Version 6.0 of Microsoft's JDBC driver for SQL Server added support for table-valued parameters.

    The following code sample shows how to

    • use a SQLServerDataTable object to hold the table data to be passed, and
    • call the SQLServerCallableStatement#setStructured method to pass that table to the stored procedure.
    SQLServerDataTable sourceDataTable = new SQLServerDataTable();   
    sourceDataTable.addColumnMetadata("SDate", java.sql.Types.DECIMAL);
    sourceDataTable.addColumnMetadata("EDate", java.sql.Types.DECIMAL);
    sourceDataTable.addColumnMetadata("PlantCode", java.sql.Types.NVARCHAR);
    sourceDataTable.addColumnMetadata("LoadType", java.sql.Types.NCHAR);
    sourceDataTable.addColumnMetadata("Asset", java.sql.Types.BIGINT);
    
    // sample data
    sourceDataTable.addRow(123, 234, "Plant1", "Type1", 123234);   
    sourceDataTable.addRow(456, 789, "Plant2", "Type2", 456789);   
    
    try (CallableStatement cs = conn.prepareCall("{CALL dbo.RegisterInitAssets (?)}")) {
        ((SQLServerCallableStatement) cs).setStructured(1, "dbo.INITVALS_MSG", sourceDataTable);
        boolean resultSetReturned = cs.execute();
        if (resultSetReturned) {
            try (ResultSet rs = cs.getResultSet()) {
                rs.next();
                System.out.println(rs.getInt(1));
            }
        }
    }
    

    For more details, see the following MSDN article:

    Using Table-Valued Parameters

    0 讨论(0)
  • 2020-12-06 22:30

    Try it this way:

    connection = dataSource.getConnection();
    CallableStatement statement = connection.prepareCall("{? = call dbo.RegisterInitAssets(?)}");
    statement.registerOutParameter(1, OracleTypes.CURSOR);//you can skip this if procedure won't return anything
    statement.setObject(2, new InitvalsMsg()); //I hope you some kind of representation of this table in your project
    statement.execute();
    
    ResultSet set = (ResultSet) statement.getObject(1);//skip it too if its not returning anything
    
    0 讨论(0)
提交回复
热议问题