3

我们在 SQL Server 中有这个用户定义的表类型:

CREATE TYPE [dbo].[INITVALS_MSG] AS TABLE(
    [SDate] [decimal](8, 0) NOT NULL,
    [EDate] [decimal](8, 0) NOT NULL,
    [PlantCode] [nvarchar](10) NOT NULL,
    [LoadType] [nchar](8) NOT NULL,
    [Asset] [bigint] NOT NULL
)

和一个以该表为输入的存储过程:

ALTER PROCEDURE [dbo].[RegisterInitAssets]
    @initmsg INITVALS_MSG ReadOnly
AS
BEGIN
    ...

现在,我需要从 java 调用这个过程。有可能做这样的事情吗?JDBC 支持这个吗?

--------编辑我在java中有一个对应于该类型的类:

public class DBInitialAsset {
    private Integer sDate;
    private Integer eDate;
    private String plantCode;
    private String loadType;
    private Integer asset;

    public DBInitialAsset() {
    }
}
4

2 回答 2

6

是的,现在可以了。Microsoft 的 SQL Server JDBC 驱动程序 6.0 版增加了对表值参数的支持。

以下代码示例显示了如何

  • 使用一个SQLServerDataTable对象来保存要传递的表数据,并且
  • 调用该SQLServerCallableStatement#setStructured方法将该表传递给存储过程。
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));
        }
    }
}

有关更多详细信息,请参阅以下 MSDN 文章:

使用表值参数

于 2017-01-01T16:40:50.177 回答
0

试试这种方式:

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
于 2013-01-27T09:11:30.527 回答