c# console app: obtaining the new id that was just created. RRS feed

  • Question


    In my console app I'm doing a insert where the newID is created SQL side as a GUID.

    I write this in hopes of obtaining that brand new GUID for that session - but it fails.


    if (BuildToWrite.Length > 0)




    Console.Write("Updating DataSet succeeded!");

    String query = "select @@identity"; //results are empty

    //String query = "select NEWID()"; //comes up with random unrelated GUID


    SqlCommand cmd = new SqlCommand(query, myConnection);

    SqlDataReader reader = cmd.ExecuteReader();

    while (reader.Read())


    EntryGuid = reader.GetGuid(0).ToString();







    Console.Write("No Changes!");

    return null;




    There was something about ExecuteScalar but that was failing differently.


    I also tried a OnUpdate (or something) - but couldn't figure out how to return the string value back to the function... unless I made the string very global.


    suggestions for my next approach?


    Monday, October 22, 2007 6:44 PM

All replies

  • What query gets executed when you call Update?


    Consider using SCOPE_IDENTITY() instead of @@IDENTITY. Also, if your database is under SQL Server 2005, use the OUTPUT clause of the INSERT statement.

    Tuesday, October 23, 2007 2:40 PM