Sql server Spring:调用具有DATE或DATETIME参数的SQL Server存储过程
在Spring Boot项目中,我尝试调用一个存储过程,该存储过程有一个日期输入参数,代码如下:Sql server Spring:调用具有DATE或DATETIME参数的SQL Server存储过程,sql-server,spring-boot,stored-procedures,spring-jdbc,Sql Server,Spring Boot,Stored Procedures,Spring Jdbc,在Spring Boot项目中,我尝试调用一个存储过程,该存储过程有一个日期输入参数,代码如下: SimpleJdbcCall jdbcCall = new SimpleJdbcCall(jdbcTemplate).withProcedureName(sp_name); MapSqlParameterSource msps = new MapSqlParameterSource(); LocalDate dateVal = LocalDate.parse(paramVal); msps.ad
SimpleJdbcCall jdbcCall = new SimpleJdbcCall(jdbcTemplate).withProcedureName(sp_name);
MapSqlParameterSource msps = new MapSqlParameterSource();
LocalDate dateVal = LocalDate.parse(paramVal);
msps.addValue(paramName, dateVal, Types.DATE);
return jdbcCall.execute(msps);
这样做将导致以下SQL错误:
org.springframework.jdbc.UncategorizedSQLException: CallableStatementCallback; uncategorized SQLException for SQL [{call sp_name(?)}]; SQL state [S0003]; error code [257]; Implicit conversion from data type varbinary to date is not allowed. Use the CONVERT function to run this query.; nested exception is com.microsoft.sqlserver.jdbc.SQLServerException: Implicit conversion from data type varbinary to date is not allowed. Use the CONVERT function to run this query.
使用DATETIME
参数也会发生同样的情况。
因此,我检查了jdbc如何使用SQL Server Profiler调用过程,并注意到使用VARBINARY
type调用参数:
exec sp_executesql N'EXEC sp_name @P0',N'@P0 varbinary(8000)',NULL
所有其他类型的输入变量(如NVARCHAR
,数值
,位
,等等)也会发生同样的情况
我在Microsoft Docs上找到了,但没有帮助:我正在使用兼容级别>120(150)的SQL Server数据库,因此根据页脚注释3,我正在将LocalDate
转换为String
,然后传递到MapSqlParameterSource
,如下所示:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
String formattedString = dateVal.format(formatter);
msps.addValue(paramName, formattedString, Types.NVARCHAR);
但是很明显,我仍然在处理相同的转换错误,因为参数仍然是以前作为VARBINARY
传递的
因此,我的问题是:
- 为什么所有的参数类型都作为
传递?我是否缺少一些代码来传递正确类型的代码VARBINARY
- 如果无法让jdbc以正确的格式传递参数,那么如何正确地传递通常无法从
转换为实际类型的参数VARBINARY