I am using Linq-to-SQL and in order to generate my linq code I write a stored procedure and drop that proc on my dbml.
I have large list of customers' name & age and I want to write query that allow to insert whole list in one call? Is this possible?
Currently I am inserting one at a time using foreach loop which takes so long to insert thousands of customers. I researched about this but didn't get exact solution.
I am new to Linq-to-SQL and stored procedures, so any help would be appreciated.
Linq is not the best approach for this task. For massive inserts I'd recommend instead Bulk Insert:
You could pass in your list as an XML item and parse out the data from that with a SQL join.
// Sample XML format
<customers>
<customer>
<name></name>
<age></age>
</customer>
</customers>
You can easily doing using an XElement object (System.Xml.Linq namespace).
You want your stored procedure to take in one parameter then: of datatype xml - you then do your insert based on the value of the nodes associated with it ( http://msdn.microsoft.com/en-us/library/ms188282.aspx )
DECLARE @item xml;
SET @item =
N'<customers>
<customer><name>Lorcan</name><age>24</age></customer>
<customer><name>Robert</name><age>20</age></customer>
</customers>';
INSERT INTO YOUR_TABLE_NAME
SELECT
T.c.query('name').value('.','varchar(max)') as Name,
T.c.query('age').value('.','int') as Age
FROM @item.nodes('/customers/customer') T(c)
Note that there is still a limit of 1,000 inserts at one time as far as I know.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.