Monday, March 26, 2012

Duplicate last record when using SqlDataAdapter.Update for Insert command

I'm getting duplicate records for the last record in the datatable. No matter how much or how little my datatable contains row records, it always duplicate the last one for some reason. Is there something wrong with my code below? EXAMID pulling from another stored procedure, which is outputed back to a variable.

--Data Access Layer--

If dt.Rows.Count > 0Then

'INSERT EXAM ROSTER

InsertComm =New SqlCommand
sqladapter =New SqlDataAdapter
InsertComm =New SqlClient.SqlCommand("ExamOfficers_AddOfficerSpecificExamRoster", conndb)
InsertComm.CommandType = CommandType.StoredProcedure

sqladapter.InsertCommand = InsertComm

InsertComm.Parameters.Add("@.examid", SqlDbType.Int)InsertComm.Parameters("@.examid").Value = examid
InsertComm.Parameters.Add("@.officerid", SqlDbType.Int, 12,"Officer_UID")
InsertComm.Parameters.Add("@.reimburse", SqlDbType.Bit, 12,"ReimburseToDb")
InsertComm.Parameters.Add("@.posttest", SqlDbType.Int, 12,"Post_Test")
InsertComm.Parameters.Add("@.pqcdate", SqlDbType.DateTime, 12,"pqc_date")
InsertComm.Parameters.Add("@.pqcscore", SqlDbType.Int, 12,"pqc_score")

conndb.Open()

sqladapter.UpdateBatchSize = 100
InsertComm.UpdatedRowSource = UpdateRowSource.None
sqladapter.Update(dt)

InsertComm.ExecuteNonQuery()
InsertComm.Dispose()

EndIf

--Stored Procedure--

ALTERPROCEDURE [dbo].[ExamOfficers_AddOfficerSpecificExamRoster]

@.ExamIDasint,
@.OfficerIDasint,
@.reimburseasbit=NULL,
@.posttestasint=NULL,
@.pqcdateasdatetime=NULL,
@.pqcscoreasint=NULL

AS
BEGIN
SETNOCOUNTON;

InsertInto Exam_Officers(EXAM_UID,Officer_UID,reimburse,post_test,pqc_date,pqc_score)
values(@.ExamID,@.OfficerID,@.reimburse,@.posttest,@.pqcdate,@.pqcscore)

END

Hi,

Try to comment this line InsertComm.ExecuteNonQuery() because it seems like that DataAdapter itself updates the database with its Update method but after that you are also running the command manually with ExecuteNonQuery. I think this is the reason why your last record is saved twice. Try it out.

Hope it will help you

Thanks and best regards,

sql

No comments:

Post a Comment