Solved

SQl Scope ID

Posted on 2009-04-14
11
440 Views
Last Modified: 2012-05-06
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);
SELECT FacID FROM [FacilityHistory] WHERE (FacID= SCOPE_IDENTITY())
 
 
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

0
Comment
Question by:dimck
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 4
  • 3
11 Comments
 
LVL 15

Expert Comment

by:oobayly
ID: 24137886
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.
0
 
LVL 70

Expert Comment

by:Éric Moreau
ID: 24137895
You don't need to select from your table. Try this:
SELECT SCOPE_IDENTITY()
0
 
LVL 70

Expert Comment

by:Éric Moreau
ID: 24137905
also what is the datatype of your NewID variable? Can it be that it is to small for the returned value?
0
Monthly Recap

May was a big month for new releases from Linux Academy! Take a look at what our team built recently in our blog. You can access the newest releases from our blog.

 

Author Comment

by:dimck
ID: 24137926
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
0
 
LVL 70

Expert Comment

by:Éric Moreau
ID: 24138172
is the expected value larger then the value of an integer?
0
 

Author Comment

by:dimck
ID: 24138189
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
                      (MemberNo)
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?
0
 
LVL 70

Expert Comment

by:Éric Moreau
ID: 24138232
0
 
LVL 15

Expert Comment

by:oobayly
ID: 24138324
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();
    adapter.Fill(table);
 
    DataRow row = table.NewRow();
    row["fldWord"] = "foo";
    table.Rows.Add(row);
 
    // 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

0
 
LVL 15

Expert Comment

by:oobayly
ID: 24138333
Clarification:
"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.
0
 

Author Comment

by:dimck
ID: 24138384
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
                      (MemberNo)
VALUES     ('22222')
                          SELECT     SCOPE_IDENTITY()
0
 

Accepted Solution

by:
dimck earned 0 total points
ID: 24142893
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.
0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

When table data gets too large to manage or queries take too long to execute the solution is often to buy bigger hardware or assign more CPUs and memory resources to the machine to solve the problem. However, the best, cheapest and most effective so…
When it comes to protecting Oracle Database servers and systems, there are a ton of myths out there. Here are the most common.
Video by: Steve
Using examples as well as descriptions, step through each of the common simple join types, explaining differences in syntax, differences in expected outputs and showing how the queries run along with the actual outputs based upon a simple set of dem…
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…

717 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question