c# - Inserting multiple rows into MS SQL Server and retrieve all the new table ID's back -


looking @ example given here: https://stackoverflow.com/a/452934

i understand need iterate through loop , append value clauses, missing how amend query return id's newly created records , retrieve them in c#?

for example current code can seen below, change insert multiple rows in 1 query , retrieve newly created id's list of integers ideally.

in_new_id = -1; string query = "insert " +   db_base.dbtable_customer_order_table + "(" + db_base.dbtable_customer_order_table_customer_id + "," + db_base.dbtable_customer_order_table_productid+")"; query += " output inserted." + db_base.dbtable_customer_order_table_id; query += " values ( @customerid, @productid);";  using (sqlconnection conn = new sqlconnection(generalconfig.db_str())) {     sqlcommand sql_command = new sqlcommand(query, conn);     sql_command.parameters.addwithvalue("@customerid", data_obj.customerid);     sql_command.parameters.addwithvalue("@productid", data_obj.productid);     if (!string.isnullorempty(query) && sql_command != null && conn != null)     {          sql_command.connection.open();          if (sql_command.connection.state == system.data.connectionstate.open)          {              object out_new_id = sql_command.executescalar();              if (out_new_id != null)              {                  in_new_id = (int)out_new_id;              }              sql_command.connection.close();              return enum_db_status.db_success;          }          else          {              in_new_id = -1;              return enum_db_status.db_connection_could_not_open;          }     } }  return enum_db_status.db_fail; 

use this:

list<int> ids = new list<int>(); using (sqlcommand command = new sqlcommand(@"declare @t table(id int)                                                                 insert yourtablename(yourtablecolumnnames)                                                                 output inserted.id @t values                                                                  (yourvalues1),                                                                 (yourvalues2),                                                                 (yourvalues3),                                                                 (etc...) select id @t ", con))                     {                         using (sqldatareader reader = command.executereader())                         {                             while (reader.read())                             {                                 int id = int.parse(reader[0].tostring());                                 ids.add(id);                             }                         }                     } 

warning!!! work if you're using sqlserver 2008 r2 or higher.
edit: damien said in comments : "there no guarantee order in changes applied table , order in rows inserted output table or table variable correspond."


Comments