I've a Stored Procedure that insert some record then update it
CREATE PROCEDURE [dbo].[InsertSponsors]
@Someparameters nvarchar(100),
@Anotherparameter int,
AS
Begin
DECLARE @ID int,
@RowCount int
insert into Clients (Name,Photo,PolicyID,BirthDay,
Gender,Title,Nationality,Relationship,ClassID,HRID,Active,
StartingDate,EndingDate,AddingDate,CreationOwner,UniqueID,PassportNo)
values (@Name,@Photo,@PolicyID,@Birthday,@Gendar,@Title,@Nationality,@RelationShip,
@ClassID,@HRID,@Active,@StartingDate,@EndingDate,@AddingDate,@CreationOwner,@UniqueID,@PassportNo)
SELECT @RowCount = @@ROWCOUNT;
Select @ID=SCOPE_IDENTITY();
update Clients set SponsorID=@ID where ID=@ID;
End
I'm Calling this Stored Procedure from DataAdapter like below
Notice: I've tried all the commented code but with no luck
internal static int UpdateInsertAdapter(string query,DataTable dt, SqlParameter[] sqlParameters, bool SP)
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = openConnection();
cmd.CommandText = query;
if (SP)
{
cmd.CommandType = CommandType.StoredProcedure;
}
cmd.UpdatedRowSource = UpdateRowSource.None;
foreach (SqlParameter parameter in sqlParameters)
{
cmd.Parameters.Add(parameter);
}
SqlDataAdapter adpt = new SqlDataAdapter();
//adpt.AcceptChangesDuringFill = true;
//adpt.AcceptChangesDuringUpdate = true;
//SqlCommandBuilder cmdb = new SqlCommandBuilder(adpt);
//adpt.InsertCommand = cmdb.GetInsertCommand();
adpt.InsertCommand = cmd;
**//////Should i've select command to select the @RowCount**
adpt.UpdateBatchSize = 10;
int recordsInserted = adpt.Update(dt);
return recordsInserted;
}
Notice:
This Datatable is modified as i read it using ExcelDataReader then i've added two DataColumns to that Datatable
Questions
what can i do to bulk insert Datatable and select the inserted rows.
In this article Codeproject Multiple Ways to do Multiple Inserts the author wrote a Stored Procedure just to insert can i insert then update
Errors:
1.Update requires a valid UpdateCommand when passed DataRow collection with modified rows
2.The DataAdapter.SelectCommand property needs to be initialized.
Update
As per jmcilhinney help i figured out the reason for error #1 and i've found a Solution at this question by user Dan by using SqlCommandBuilder.
SqlCommandBuilder cmdb = new SqlCommandBuilder(adpt);
adpt.InsertCommand = cmd;
adpt.UpdateCommand = new SqlCommandBuilder(adpt).GetUpdateCommand();
but when i use these lines error #2 occurs.