ExecuteScalar error

Hi guys some help please.

I have this sp:


ALTER PROCEDURE dbo.sp_CreateProject
(
@UserKey int,
@RetailerCompanyKey int,
@ProjectTitle nvarchar(50)
)

AS
DECLARE @ProjectKey int

SET @ProjectKey = 0

SET NOCOUNT ON
      If Exists(Select ProjectTitle from Project Where ProjectTitle = @ProjectTitle)
      
            return @ProjectKey
      Else
      Begin
            insert into Project ([ProjectUserKey],[ProjectTitle],[RetailerCompanyKey], [ProjectCreatedOn]) values (@UserKey,@ProjectTitle,@RetailerCompanyKey,getDate())
            Set @ProjectKey = @@IDENTITY
      End


      IF NOT @ProjectKey IS NULL      
      Begin
            insert into ProjectBrief (ProjectKey) values (@ProjectKey)

            insert into ProjectStatus(ProjectKey,StatusKey,ChangeDate) values (@ProjectKey,'1',getDate())
      End
RETURN @ProjectKey

I call this sp with the following code:

public int NewProject(int userkey, int retailer, string title)
            {
                  SqlParameter[] parameters = new SqlParameter[3];

                  parameters[0] = new SqlParameter("@UserKey", System.Data.SqlDbType.Int,4);
                  parameters[0].Value = userkey;

                  parameters[1] = new SqlParameter("@RetailerCompanyKey", System.Data.SqlDbType.Int,4);
                  parameters[1].Value = retailer;

                  parameters[2] = new SqlParameter("@ProjectTitle", System.Data.SqlDbType.NVarChar,50);
                  parameters[2].Value = title;
                  
                  object obj =SqlHelper.ExecuteScalar(Connection.ConnectionString, CommandType.StoredProcedure, "sp_CreateProject",parameters);
                  if (obj == System.DBNull.Value)
                  {
                        return 0;
                  }
                  else
                  {
                        return (int) obj;
                  }
            }

Instead of returning the next project number it crashs with an error stating that object is not set to an instance of an object.

If I change the ExecuteScalar to ExecuteNonQuery I get -1 returned.

Any help would be mostly appreciated

Wayne
wathertonAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

SRigneyCommented:
ExecuteScalar is for looking at the first field of a select statement.  So you definitely don't want to do that.

I can see that you are returning items.  What you want to do is add add a return value

SqlCommand cmd = new SqlCommand();
cmd.Connection = Connection;
cmd.CommandText = "sp_CreateProject";
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.Add("@UserKey", System.Data.SqlDbType.Int,4);
cmd.Parameters["@UserKey"].Value = userkey;
cmd.Parameters.Add("@RetailerCompanyKey", System.Data.SqlDbType.Int,4);
cmd.Parameters["@RetailerCompanyKey"].Value = retailer;
cmd.Parameters.Add("@ProjectTitle", System.Data.SqlDbType.NVarChar,50);
cmd.Parameters["@ProjectTitle"].Value = title;
cmd.Parameters.Add("RETURN_VALUE", System.Data.SqlDbType.Int,4);
cmd.Parameters["RETURN_VALUE"].Direction = ParameterDirection.ReturnValue;

cmd.ExecuteNonQuery();
Console.Writeline( Convert.ToInt32(cmd.Parameters["RETURN_VALUE"].Value) );
0
melodiesoflifeCommented:
Hi  watherton

+ The ExecuteScalar method returns the first column of the first row of data returned by the command, no matter how many rows the command actually selects.

when you call:

return (int) obj;

it crashed because the obj in your code may not be a number.

+ The ExecuteNonQuery method return the number of rows have been update, so in this case you should used ExecuteNonQuery rather than ExecuteScalar
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C#

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.