Used after the SQL statement
Scope_identity ()
Of course, you can also use the SELECT @ @IDENTITY
But using the SELECT @ @IDENTITY is the latest in the global. It is possible to obtain an incorrect value.
Example:
Copy Code code as follows:
INSERT INTO dbo. Sns_blogdata (UserName) VALUES (' Jiangyun ');
SELECT scope_identity ()
gets the primary key return value of the Sql-server database insert into operation, scope_identity
When you insert a record, you want to get the primary key return value from its datasheet immediately. This primary key is automatically generated, in fact, there are many ways to implement, such as another query to get out. Or to remove the maximum value before inserting the data, add one to the maximum and so on, there are many ways, but some are inconvenient.
The quickest way to personally feel is to get the value of the primary key directly after inserting the data, and then come back.
The method is as follows:
The SQL statement is as follows:
INSERT into TableName (fieldname ...) VALUES (value ...) SELECT @ @IDENTITY as Returnname;
Add the SELECT @ @IDENTITY as returnname in the SQL statement; to get the value of the primary key
To get the return value in the program:
Copy Code code as follows:
public int Sqlexecutereader (String sql)
{
Dbopen ();
SqlCommand Mycomm = new SqlCommand (sql, Connection);
int NewID = Convert.ToInt32 (Mycomm.executescalar ());
Dbclose ();
return NewID;
}
Of course here the primary key is an automatic increment of type int. The operation of the dbopen ();D bclose () is not much said here.
Select Scope_identity ()
Returns the value of the identity column of the last row in the data table above;
Returns the last identity value in the identity column inserted into the same scope. One scope is a module--stored procedures, triggers, functions, or batches. As a result, if two statements are in the same stored procedure, function, or batch, they are in the same scope.
SELECT @ @IDENTITY
Returns the value of the identity column of the last row of the last data table in the above operation;
To create a table:
CREATE TABLE T_user (f_id int identity (1,1) not null,f_name varchar (.) NOT NULL)
Insert data:
Insert into T_user (f_name) VALUES (' Who am I ') Select scope_identity ()
Stored procedures:
CREATE PROCEDURE [dbo]. [Sp_user] (@F_Name int) As
BEGIN Tran Insertinto_t_user
Insert into dbo. T_user (F_name) VALUES (@F_Name)
Select scope_identity ()