[英]How to pass the values of user defined datatype variable to MS SQL from java using spring jdbc store procedure
我有以下帶有用戶定義的變量( @Location
MS SQL存儲過程
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
提示這一點。)
根據SQL Server論壇上的這篇文章 ,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();
(我發現它更有助於調用executeQuery()
上的PreparedStatement比execute()
我沒有你的存儲過程的代碼,所以我做了Organization_Insert
提高其消息包含的行數表中的變量。使用錯誤executeQuery()
是使此錯誤消息拋出SQLException所必需的:使用execute()
不會引發任何異常。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.