|
Currently when I have to insert multiple rows into a table the only way I know how to do it is to just brute force it. For example if I need to insert 6 product IDs for a person I code inserts which seems inelegant; is there any other way?
(comments are locked)
|
|
INSERT - VALUES Depending on your version of SQL Server, you may not have to use multiple SQL Statements. In SQL Server 2008, you can use multiple comma-separated values for INSERT statements. Here is a working example
Importing through Bulk Import You can use text/CSV/Native format files and Bulk Import to fill data into your tables. I like the multiple VALUE clause approach. Nice and clean.
Dec 14 '09 at 05:13 PM
David Wimbush
This is exactly what I was looking for! Thank you!
Dec 14 '09 at 05:47 PM
user-753
Same comment as on the other method like this. This has the exact same problem. However, if you use SQL 2008, a Table Valued Parameter solves that problem. http://msdn.microsoft.com/en-us/library/bb675163.aspx
Dec 14 '09 at 09:33 PM
Jonathan Kehayias
(comments are locked)
|
|
Another common method I've seen is like this: Wow! Even better for those older SQL versions.
Dec 14 '09 at 06:58 PM
user-753
Keep in mind that this can't be done easily using parameterization so you either have a SQL Injection risk or complex code to handle adding a parameter for each column, for each row dynamically.
Dec 14 '09 at 09:45 PM
Jonathan Kehayias
(comments are locked)
|
|
A common method of doing this is to pass an XML document to a stored procedure and use OPENXML or XQUERY to shred the XML document and perform the insert in a single statement.
(comments are locked)
|
|
Another mechanism is to pass a comma-delimited list and pivot it into a table, preferably through the use of queries, but possibly through user defined functions.
(comments are locked)
|


If you provide your table structure and statements a better answer can be provided.