Getting @@IDENTITY from TableAdapter

前端 未结 7 2204
自闭症患者
自闭症患者 2020-12-19 20:21

I am trying to complete a seemingly simple task that has turned into a several hour adventure: Getting @@Identity from TableAdapter.Insert().

7条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-19 20:45

    The real answer:

    • read the notes below!

    Get identity from tableadapter insert function

    I keep getting questions about this issue very often and never found time to write it down.

    Well, problem is following: you have table with primary key with int type defined as Identity and after insert you need to know PK value of newly inserted row. Steps for accomplishing to do this are following:

    use wizard to add new insert query (let's call it InsertQuery) in the body of query just add SELECT SCOPE_IDENTITY() at the bottom after saving this query, change ExecuteMode property of this query from NonQuery to Scalar in your code write following (ta is TableAdapter instance) :

    int id;
    
    try
    {
     id = Convert.toInt32(ta.InsertQuery(firstName, lastName, description));
    }
    catch (SQLException ex)
    {
    //...
    }
    finally
    {
    //...
    }
    

    Make money with this! :) Posted 12th March 2009 by Draško Sarić

    From: http://quickdeveloperstips.blogspot.nl/2009/03/get-identity-from-tableadapter-insert.html

    Notes:

    • Setting the ExecutMode to Scalar is possible via the Properties of your generated Insert Query. (press F4).

    • In my version (Visual Studio 2010 SP1 ) the select statement was generated automatically.

提交回复
热议问题