0
votes

I have an insert stored procedure like this

  if exists(select EmailId from Profile_Master where EmailId=@EmailId)
set @result=-1
else
begin
set @result=0


 insert into Profile_Master(FirstName,LastName,Dob,Gender,MobileNo,Country,State,EmailId,Password)
 values 
(@FirstName,@LastName,@Dob,@Gender,@MobileNo,@Country,@State,@EmailId,@Password)
set @id=SCOPE_IDENTITY()
return
end 

 pid = cmd1.Parameters.Add("@id", SqlDbType.Int);
            pid.Direction = ParameterDirection.Output;
            cmd1.ExecuteNonQuery();
            int res = Convert.ToInt32(pid.Value);

I am catching the value of last inserted record but i am getting an error like

Object cannot be cast from DBNull to other types.How to catch the value of last inserted record?

2
if you are expecting ID to come back with an identity value are you sure the table definition of Profile_Master actually includes an identity column? - blowdart
userid column is the identity column in the table. - Chandra sekhar
Are you sure? If @id is null then either a) the identity column isn't be populated or b) the stored procedure parameter list has forgotten to mark id as output. - You should edit and include the WHOLE sp definition, including the create line and the table definition - blowdart

2 Answers

2
votes

Do a null-check before you try to convert the value.

if( pid.Value is DBNull )
{
    // Do alternative route.
}
else
{
    int res = Convert.ToInt32(pid.Value);
}

or:

if( ! pid.Value is DBNull )
{
    int res = Convert.ToInt32(pid.Value);
}
1
votes

Well, clearly we can assume that pid.Value is equal to DBNull.Value and cannot be converted to type int

You need to check what the sp does adn what it returns from the Database.