我有以下带有用户定义变量的 MS SQL 存储过程 (@Location
CREATE PROCEDURE [Organization].[Organization_Insert]
(
@OrganizationID NVARCHAR(256),
@Location Locationtype ReadOnly
)
@Location
具有以下属性:OrganizationSubID、LocationCode
我使用下面的java类来调用存储过程,
class OrganizationInsertProcedure extends StoredProcedure {
private final String[] outputParameters = new String[] {OUTPUT};
public PlanActivityInsertProcedure(DataSource dataSource) {
super(dataSource, "Organization_Insert");
declareParameter(new SqlParameter("@OrganizationID", Types.NVARCHAR));
declareParameter(new SqlParameter("@Location", Types.ARRAY, "Locationtype"));
compile();
}
这里,我的问题是,如何从java构造@Location
变量并将其传递到MS SQL数据库。 (正在使用sqljdbc4.jar驱动程序连接数据库)
我一整天都在 Google 上搜索并尝试了很多实现,但没有任何返回。
请有人阐明这一点......
最佳答案
(我假设您已将 Locationtype
声明为表变量。在存储过程的参数上使用 ReadOnly
暗示了这一点。)
According to this post on the SQL Server forums ,Microsoft SQL Server JDBC 驱动程序当前不支持表变量。因此,看来您必须构建一串 T-SQL,它声明一个表变量,将数据插入表中,然后执行存储过程。
在“普通”JDBC 中,即不使用 Spring,执行此操作的代码如下所示:
int numRows = /* number of rows in table variable */;
StringBuilder sqlBuilder = new StringBuilder("DECLARE @Location AS LocationType;");
for (int i = 0; i < numRows; ++i) {
sqlBuilder.append(
"INSERT INTO @Location (OrganizationSubID, LocationCode) VALUES (?, ?);");
}
sqlBuilder.append("EXEC [Organization].[Organization_Insert] ?, @Location;");
PreparedStatement stmt = connection.prepareStatement(sqlBuilder.toString());
for (int i = 0; i < numRows; ++i) {
stmt.setString(i * 2 + 1, /* OrganizationSubID for row i */);
stmt.setString(i * 2 + 2, /* LocationCode for row i */);
}
stmt.setString(numRows * 2 + 1, /* Organization ID */);
ResultSet resultSet = stmt.executeQuery();
resultSet.close();
(我发现在PreparedStatement上调用 executeQuery()
比 execute()
更有帮助。我没有你的存储过程代码,所以我让 Organization_Insert
引发一个错误,其消息包含表中的行数变量。需要使用 executeQuery()
才能在 SQLException 中抛出此错误消息:使用 execute()
不会引发异常。)
关于java - 如何使用 spring jdbc 存储过程将用户定义的数据类型变量的值从 java 传递到 MS SQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26903045/