[英]Passing a user-defined table type to a SQL Server stored procedure using JDBC
We've got this User-Defined-Table Type in SQL Server:我们在 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
)
and a Stored Procedure which takes that table as input:以及一个将该表作为输入的存储过程:
ALTER PROCEDURE [dbo].[RegisterInitAssets]
@initmsg INITVALS_MSG ReadOnly
AS
BEGIN
...
Now, I need to call this procedure from java.现在,我需要从 java 调用这个过程。 Is it possible to do such a thing?
有可能做这样的事情吗? Does JDBC support this?
JDBC 支持吗?
--------EDIT I have a corresponding class in java for that type: --------编辑我在java中有一个对应的类用于该类型:
public class DBInitialAsset {
private Integer sDate;
private Integer eDate;
private String plantCode;
private String loadType;
private Integer asset;
public DBInitialAsset() {
}
}
Yes, it is now possible.是的,现在可以了。 Version 6.0 of Microsoft's JDBC driver for SQL Server added support for table-valued parameters.
Microsoft 用于 SQL Server 的 JDBC 驱动程序的 6.0 版增加了对表值参数的支持。
The following code sample shows how to以下代码示例显示了如何
SQLServerDataTable
object to hold the table data to be passed, andSQLServerDataTable
对象来保存要传递的表数据,以及SQLServerCallableStatement#setStructured
method to pass that table to the stored procedure.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));
}
}
}
For more details, see the following MSDN article:有关更多详细信息,请参阅以下 MSDN 文章:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.