ExecuteScalar method sometimes work, sometimes doesn't

R

Randy Smith

Hi,

I've got some weird behavior happening within one of the datamappers. It
all has to do with inserting a new row, and returning the Id of the row
being entered.



Here is what the code looks like that is getting "Object reference not set
to an instance ..." run-time error:

string ateId = cm.ExecuteScalar().ToString(); ß------------
this line crashes

None of the parameters are null, nor do they appear to have any illegal data
inside of them. The above code inserts a row into the AuditTrailEntry
table.



On the other hand, this code inserts a new jobStep row, and doesn't cause
any errors:

if (storedProcedure == "updateJobStep") //use this if update

cm.ExecuteNonQuery(); // no return value needed

else

{

string jobStepId = cm.ExecuteScalar().ToString(); //insert new
jobStep, get id of new row

js.Id = Convert.ToInt16(jobStepId);

}



Does anyone see a problem with this code, or know why it doesn't work?



TIA, Randy
 
B

bruce barker

ExcuteScalar returns the first column value of the first row of the
first result set. if the first result set has no rows, this routine will
throw an error. would need the sp code to determine why the first result
set has no rows.

-- bruce (sqlwork.com)
 
R

Randy Smith

Hi,
One of my coworker programmers solved the problem. The actual stored
procedure MUST return the value needed with code such as this:
SELECT SCOPE_IDENTITY() AS [AuditTrailEntriesId] //REPLACE
"AuditTrailEntriesId" with the name of the field you need to have returned

HTH, Randy
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,042
Latest member
icassiem

Latest Threads

Top