Home >Database >Mysql Tutorial >What is the MySQL Equivalent of SQL Server\'s SCOPE_IDENTITY()?

What is the MySQL Equivalent of SQL Server\'s SCOPE_IDENTITY()?

Linda Hamilton
Linda HamiltonOriginal
2024-11-19 06:25:02405browse

What is the MySQL Equivalent of SQL Server's SCOPE_IDENTITY()?

MySQL Equivalent of SQLServer's SCOPE_IDENTITY()

In MySQL, the equivalent function to SCOPE_IDENTITY() in SQLServer is LAST_INSERT_ID(). This function returns the generated ID of the last inserted row in the current session.

How to Use LAST_INSERT_ID()

LAST_INSERT_ID() can be used in various scenarios to retrieve the ID of a newly inserted record. For instance, consider the following code:

CREATE TABLE users (
  id INT AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(255)
);

INSERT INTO users (name) VALUES ('John Doe');

SELECT LAST_INSERT_ID();

In this example, the LAST_INSERT_ID() function returns the ID of the newly inserted user, which is 1 in this case.

Behavior Within Triggers

It's important to note that LAST_INSERT_ID() operates within the scope of the current session. If you use it within a trigger, it will return the ID of the last inserted row in the table that the trigger is attached to, not in the table that triggered the insertion.

The above is the detailed content of What is the MySQL Equivalent of SQL Server's SCOPE_IDENTITY()?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn