Wednesday, March 21, 2012

ExecuteScalarProblem

 In my application Im inserting data into the database and returning the ID of the new record, to do this I have the following stored procedure: 
 
ALTER PROCEDURE Turbo_InsertAppChange(@.app_namevarchar(50),@.app_developerchar(3),@.app_rq_numchar(10),@.app_completition_datedatetime, @.app_descriptionvarchar(1500))AS SET NOCOUNT ON INSERT INTO Turbo_Change_Log(app_name,app_developer,app_rq_num,app_completition_date,app_description,date_entered)SELECT @.app_name, @.app_developer, @.app_rq_num,CONVERT(DATETIME,@.app_completition_date), @.app_description,GETDATE()SELECT SCOPE_IDENTITY()
Where I use this procedure I have this code:

 
Protected Sub EnterAppInfo()'##INSERT APP INFO## sSQL ="Turbo_InsertAppChange" Command =New SqlCommand(sSQL, Connection) Command.CommandType = CommandType.StoredProcedure Command.Parameters.Add("@.app_name", SqlDbType.VarChar).Value = application_name.Text.ToString Command.Parameters.Add("@.app_developer", SqlDbType.Char).Value = developer_list.SelectedValue.ToString Command.Parameters.Add("@.app_rq_num", SqlDbType.VarChar).Value = rq_num.Text.ToString Command.Parameters.Add("@.app_completition_date", SqlDbType.DateTime).Value =CType(Api_calendar1.DDate,Date) Command.Parameters.Add("@.app_description", SqlDbType.VarChar).Value = proj_desc.Text.ToStringTry Connection.Open()Dim NewIdAs Integer =CType(Command.ExecuteScalar(),Integer)
...

But I'm getting theObject reference not set to an instance of an object error at theDim NewId As Integer = CType(Command.ExecuteScalar(),Integer) line. When I run this procedure alone in QueryAnalyzer it returns the ID like its supposed to, but when I run it in my application I get the above error. What am I doing wrong here?

ExecuteScalar return null reference if the result set is empty.

So you convert a null object to integer which cause the error:

CType(Command.ExecuteScalar(),Integer)

You can catch the exeption and return 0(means null).

No comments:

Post a Comment