Solved

SQl Scope ID

Posted on 2009-04-14
11
406 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
  • 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 69

Expert Comment

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

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
 

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 69

Expert Comment

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

Hassle-free live chat software re-imagined for business growth. 2 users, always free.

 

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 69

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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
Use this article to create a batch file to backup a Microsoft SQL Server database to a Windows folder.  The folder can be on the local hard drive or on a network share.  This batch file will query the SQL server to get the current date & time and wi…
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…

863 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

Need Help in Real-Time?

Connect with top rated Experts

24 Experts available now in Live!

Get 1:1 Help Now