Gets the ID of the current row inserted with the Access database MSSQLServer

Source: Internet
Author: User
Tags mssqlserver

//MSSQLServer  Public Static intGetinsertid (stringSQL) {        Try{SqlCommand cmd=NewSqlCommand (); using(SqlConnection conn =NewSqlConnection (connectionString)) {PrepareCommand (CMD, conn, SQL,NULL); Cmd.                ExecuteNonQuery (); PrepareCommand (CMD, conn,"Select @ @Identity",NULL); intval =Convert.ToInt32 (cmd.                ExecuteScalar ()); returnVal; }        }        Catch(Exception err) {Throwerr; }    }Private Static voidPrepareCommand (SqlCommand cmd, SqlConnection conn,stringCmdtext, SqlTransaction Trans) {        Try        {            if(Conn. State! =ConnectionState.Open) {conn.            Open (); } cmd. Connection=Conn; Cmd.commandtext=Cmdtext; if(Trans! =NULL) {cmd. Transaction=Trans; } Cmd.commandtype=CommandType.Text; }        Catch(Exception err) {Throwerr; }    }//Access Public Static intGetinsertid (stringSQL) {        Try{OleDbCommand cmd=NewOleDbCommand (); using(OleDbConnection conn =NewOleDbConnection (ConnectionString)) {PrepareCommand (CMD, conn, SQL,NULL); Cmd.                ExecuteNonQuery (); PrepareCommand (CMD, conn,"Select @ @Identity",NULL); intval =Convert.ToInt32 (cmd.                ExecuteScalar ()); returnVal; }        }        Catch(Exception err) {Throwerr; }        } Public Static voidPrepareCommand (OleDbCommand cmd, OleDbConnection conn,stringCmdtext, OleDbTransaction Trans) {        Try        {            if(Conn. State! =ConnectionState.Open) {conn.            Open (); } cmd. Connection=Conn; Cmd.commandtext=Cmdtext; if(Trans! =NULL) {cmd. Transaction=Trans; } Cmd.commandtype=CommandType.Text; }        Catch(Exception err) {Throwerr; }    }

There is also a method that can be obtained by querying the maximum ID of the current table after inserting, but if the data concurrency is large, the problem may occur

Gets the ID of the current row inserted with the Access database MSSQLServer

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.