ExecuteScalar() Returns Null

Last post 08-31-2007 8:31 PM by mstrsftwr. 3 replies.

Sort Posts:

  • ExecuteScalar() Returns Null

    07-03-2007, 3:28 AM
    • Loading...
    • matmc
    • Joined on 05-25-2007, 4:48 AM
    • Posts 12

    Hi All,

    I'm trying to insert a new record into my SQL Server dataabse. The first column is an automatically-generated identity field. I want to retrieve the ID number of the new row when I add the record using,

     

    string NewID = command.ExecuteScalar().ToString();
    For some reason, the ExecuteScalar() method throws a NullReferenceException, so I'm guessing it's not returning everything, and I'm not sure why. Can anyone help?
    Cheers,
    Mat
    Filed under: , ,
  • Re: ExecuteScalar() Returns Null

    07-03-2007, 6:20 AM
    Answer

    retreive the id after insertion because there is no Id until the record is inserted as its autogenerated.

    Please Mark Post that helped you as answer, also include a summary of what solved the problem as it helps others in similar situations
  • Re: ExecuteScalar() Returns Null

    07-03-2007, 8:16 PM
    • Loading...
    • matmc
    • Joined on 05-25-2007, 4:48 AM
    • Posts 12

    So this would do the right thing?

    1    command.ExecuteScalar();  //Execute the insert statement
    2    command.CommandText = "SELECT MAX(ID) FROM tblMyTable;";
    3    string NewID = command.ExecuteScalar().ToString();  //Get the new ID
    

    Cheers,

    Mat

  • Re: ExecuteScalar() Returns Null

    08-31-2007, 8:31 PM
    • Loading...
    • mstrsftwr
    • Joined on 08-08-2007, 9:38 PM
    • Posts 54

    execute the insert command  then the next line

     

    "INSERT INTO tblMyTable.tablecolumns values (yourvalue); SELECT id FROM tblMyTable ORDER BY id DESC;"

    string newid = command.executescalar()

     

    Scalar executes the insert command and returns the first column of the first row in the
    resultset returned by the query.

    This is also assuming that the id column from the table is an identity seed.


     

Page 1 of 1 (4 items)
Microsoft Communities
Page view counter