SQl Scope ID

I have a winforms app which inserts records into a table and should return the ID. It was working but for some reason has stopped.
I have changed my code so many times now in an attempt to fix this but I cannot get it to workl correctly.
It keeps returning the value of 1 which , I presume is the number of rows affected as opposed to the ID of the row affected.
Please help!!
SQL INsert statement
INSERT INTO [FacilityHistory] ([Memberno], [RegNo], [Sport], [Nature], [Class], [Type], [DateofEvent], [Duration], [Starttime], [ReportTime], [ReportPlace], [LeavewithPay], [LeaveOwnTime], [Remarks], [M1], [R1], [M2], [R2], [M3], [R3], [M4], [R4], [M5], [R5], [M6], [R6], [M7], [R7], [M8], [R8], [M9], [R9], [M10], [R10], [M11], [R11], [M12], [R12], [M13], [R13], [OM1], [OR1], [OM2], [OR2]) VALUES (@Memberno, @RegNo, @Sport, @Nature, @Class, @Type, @DateofEvent, @Duration, @Starttime, @ReportTime, @ReportPlace, @LeavewithPay, @LeaveOwnTime, @Remarks, @M1, @R1, @M2, @R2, @M3, @R3, @M4, @R4, @M5, @R5, @M6, @R6, @M7, @R7, @M8, @R8, @M9, @R9, @M10, @R10, @M11, @R11, @M12, @R12, @M13, @R13, @OM1, @OR1, @OM2, @OR2);
code behind statement 
NewID = FacilityHistoryTableAdapter.InsertQuery1(MemNo, strRegNo1, cboSpraSection.SelectedValue, TextBox6.Text, _
                                                  f1, cboType.SelectedIndex, dtp1.Value, nud1.Value, ST, _
                                                 RT, TextBox1.Text, nud2.Value, nud3.Value, TextBox2.Text, _
       M1, M2, M3, M4, M5, M6, M7, M8, M9, M10, M11, M12, M13, _
       R1, R2, R3, R4, R5, R6, R7, R8, R9, R10, R11, R12, R13, OM1, OM2, OR1, OR2)

Open in new window

Who is Participating?
dimckConnect With a Mentor Author Commented:
Found the problem,
Right click in the dataset designer query, properties  and change the execute mode to scalar.Works fine now.
thanks for all your advice earlier.
As long as the Insert & Select are executed in the same command, the value for FacID in the underlying row should be updated with the new Identity value.
Éric MoreauSenior .Net ConsultantCommented:
You don't need to select from your table. Try this:
Improve Your Query Performance Tuning

In this FREE six-day email course, you'll learn from Janis Griffin, Database Performance Evangelist. She'll teach 12 steps that you can use to optimize your queries as much as possible and see measurable results in your work. Get started today!

Éric MoreauSenior .Net ConsultantCommented:
also what is the datatype of your NewID variable? Can it be that it is to small for the returned value?
dimckAuthor Commented:
Hi thanks for the quick response, I have changed it to your suggestion and it still returns a value of 1.
The datatype is integer
Éric MoreauSenior .Net ConsultantCommented:
is the expected value larger then the value of an integer?
dimckAuthor Commented:
no, there are only about 20 records so it should return the next number, being 21 for example.

I have tried a query directly into sql itself
INSERT INTO FacilityHistory
VALUES     (22222)
                          SELECT     SCOPE_IDENTITY()
It comes back with a messagebox say 1 rows affected.
Why would it return rows affecrted and not row id?
Éric MoreauSenior .Net ConsultantCommented:
Because that's the way a TableAdapter works, if you look at the code that actually runs from FacilityHistoryTableAdapter.InsertQuery, you'll see it calls something like
int returnValue = this.Adapter.InsertCommand.ExecuteNonQuery();

ExecuteQuery returns the number of records affected (Deleted, Inserted or Updated).

The reason SELECT SCOPE_IDENTITY() is executed after the insert is that it tells the TableAdapter what the value created by the server for FacID is. Personally, I'd alter it to SELECT SCOPE_IDENTITY() AS FacID, as without the column alias the TableAdapter doesn't know which field to update.

Once you've called insert, you'll have look through the dataset for the newest record added, and from that you should be able to retrieve the FacID

Have a look at how this code works, this is basically what happens under the hood of your typed dataset. The only thing it's not doing is giving you the Identity value back
    /* tblWords:
     *  fldID INT NOT NULL IDENTITY(1,1)
     *  fldWord VARCHAR(255) NOT NULL
    SqlConnection conn = Global.Connection;
    SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM tblWords", conn);
    adapter.InsertCommand = new SqlCommand("INSERT INTO tblWords(fldWord) VALUES(@fldWord);" +
      "SELECT SCOPE_IDENTITY() AS fldID", conn);
    adapter.InsertCommand.Parameters.Add("fldWord", SqlDbType.VarChar).SourceColumn = "fldWord";
    DataTable table = new DataTable();
    DataRow row = table.NewRow();
    row["fldWord"] = "foo";
    // This contains 1 as only 1 row inserted
    int insertedRows = adapter.Update(table);
    // This contains the IDENTITY value created by the server
    int newID = (int)row["fldID"];

Open in new window

"The only thing it's not doing is giving you the Identity value back" refers to the typed dataset not giving the Identity value back.
dimckAuthor Commented:
I have read through the link ytou sent and it is above me to be honest.
All I did in the past was use the Visual Studio IDE wizard to generate the insert query and it worked ok, returning the FacID of the added record.

Should the simple query directly entered using enterprise manager on the database directly, return the required value, as it's not!
INSERT INTO FacilityHistory
VALUES     ('22222')
                          SELECT     SCOPE_IDENTITY()
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.

All Courses

From novice to tech pro — start learning today.