I'm using Spring JDBCTemplate to connect to the SQL Server.
I have a list of Objects that needed to be inserted into a table of SQL Server.
What I did is the following:
public void batchInsert(final List<Bean> list) {
final String sql = "insert into temp"
+ "(id, name, amount, location, time, price) "
+ " values (?, ?, ?, ?, ?, ?)";
getJdbcTemplate().batchUpdate(sql, new BatchPreparedStatementSetter() {
@Override
public void setValues(PreparedStatement ps, int i) throws SQLException {
Bean vo = list.get(i);
ps.setString(1, vo.getId());
ps.setString(2, vo.getName());
ps.setDouble(3, vo.getAmount());
ps.setString(4, vo.getLocation());
ps.setString(5, vo.getTime());
ps.setDouble(6, vo.getPrice());
}
@Override
public int getBatchSize() {
return list.size();
}
});
}
But now, I'd like to pass the parameter List<Bean> list
to a stored procedure which handle the batch insert as high efficient as possible.
May I ask how to implement this?
CREATE FUNCTION dbo. SplitInts ( @List VARCHAR(MAX), @Delimiter VARCHAR(255) ) RETURNS TABLE AS RETURN ( SELECT Item = CONVERT(INT, Item) FROM ( SELECT Item = x.i.value('(./text())[1]', 'varchar(max)') FROM ( SELECT [XML] = CONVERT(XML, '<i>' + REPLACE(@List, @Delimiter, '</i><i>') + '</i>'). query('.
Setting up multiple parameters is very easy to do. You just need to list each parameter and the data type separated by a comma as shown below.
There are several ways to do this. While using older versions of SQL Server, I've used to the XML method to pass array or list to stored procedure. In the latest versions of SQL Server, we can use the User Defined Data Type (UDT) with a base type of table to send array or list through a parameter.
After the name of the procedure, the list of parameters must be specified in the parenthesis. The parameter list must be comma-separated. The SQL Queries and code must be written between BEGIN and END keywords.
First of all don't write query directly as it can be security breach to Your application. For bulk data storage the way normally get followed is XML Way. Try to implement it through XML.
You can use Table variable parameter for your stored procedure :
CREATE TYPE RecordList AS TABLE (Id Int, Name NVarChar(100), Amount int, location nvarchar(100), ...)
CREATE PROCEDURE test
@RecordList dbo.RecordList READONLY
AS Begin
Insert Into temp (id, name, amount, location , ...)
Select id, name, amount, location, ...)
from @RecordList
End
I don't work with Spring JDBCTemplate but you can use following reference in order to use table variable parameter in C#:
How to pass table value parameters to stored procedure from .net code
C# and Table Value Parameters
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With