Insert a record and immediately obtain the primary key returned from the data table. This primary key is automatically generated. In fact, there are many implementation methods, such as performing another query and obtaining it. You can also extract the largest value before inserting data, and add one to the largest value. There are many methods, but some are inconvenient. Personally, the fastest way is to insert data
Insert a record and immediately obtain the primary key returned from the data table. This primary key is automatically generated. In fact, there are many implementation methods, such as performing another query and obtaining it. You can also extract the largest value before inserting data, and add one to the largest value. There are many methods, but some are inconvenient. Personally, the fastest way is to insert data
Insert a record and immediately obtainPrimary KeyReturn Value. This primary key is automatically generated. In fact, there are many implementation methods, for example, once againQuery. You can also extract the maximum value before inserting data and add one to the maximum value. There are many methods, but some are inconvenient.
In my opinion, the fastest way is to directly obtain the value of the primary key after inserting data, and then return it.
The method is as follows:
The SQL statement is as follows:
Insert into tableName (fieldname...) values (value...) SELECT @ identity as returnName; |
Add SELECT @ identity as returnName to the SQL statement to obtain the value of the primary key.
Obtain the return value in the program:
Public int sqlexecutereader (string SQL) { DBopen (); SqlCommand myComm = new SqlCommand (SQL, Connection ); Int newID = Convert. ToInt32 (myComm. ExecuteScalar ()); DBclose (); Return newID; } |
Of course, the primary key is automatically added for the int type here. The operations of DBopen (); DBclose (); are not described here.