首頁  >  文章  >  資料庫  >  相當於 MySQL 中的 SQL Server 函數 SCOPE_IDENTITY()?

相當於 MySQL 中的 SQL Server 函數 SCOPE_IDENTITY()?

PHPz
PHPz轉載
2023-09-10 15:49:021248瀏覽

相当于 MySQL 中的 SQL Server 函数 SCOPE_IDENTITY()?

SQL Server 函數 SCOPE_IDENTITY() 相當於 MySQL 中的 LAST_INSERT_ID()。語法如下:

SELECT LAST_INSERT_ID().

這將傳回最後插入的記錄的 ID。

在這裡,我將建立一個帶有主鍵列的表。下面是last_insert_id()的示範。

首先,讓我們建立兩個表。建立第一個表的查詢如下:

mysql> create table TestOnLastInsertIdDemo
   -> (
   -> StudentId int NOT NULL AUTO_INCREMENT,
   -> PRIMARY KEY(StudentId)
   -> );
Query OK, 0 rows affected (0.95 sec)

現在建立第二個表。查詢如下:

mysql> create table TestOnLastInsertIdDemo2
   -> (
   -> Id int NOT NULL AUTO_INCREMENT,
   -> PRIMARY KEY(Id)
   -> );
Query OK, 0 rows affected (2.79 sec)

使用插入指令在表格中插入一些記錄。查詢如下:

mysql> insert into TestOnLastInsertIdDemo2 values(),(),(),(),(),(),(),();
Query OK, 8 rows affected (0.21 sec)
Records: 8 Duplicates: 0 Warnings: 0

現在在表格「TestOnLastInsertIdDemo2」上建立一個觸發器。建立表格的查詢如下:

mysql> delimiter //
mysql> create trigger insertingTrigger after insert on TestOnLastInsertIdDemo
   -> for each row begin
   -> insert into TestOnLastInsertIdDemo2 values();
   -> end;
   -> //
Query OK, 0 rows affected (0.19 sec)
mysql> delimiter ;

如果要在 TestOnLastInsertIdDemo 表中插入記錄,last_insert_id() 傳回 1。插入記錄的查詢如下:

mysql> insert into TestOnLastInsertIdDemo values();
Query OK, 1 row affected (0.31 sec)

使用函數last_insert_id()。查詢如下:

mysql> select last_insert_id();

以下是輸出:

+------------------+
| last_insert_id() |
+------------------+
|                1 |
+------------------+
1 row in set (0.00 sec)

在上面的範例輸出中,它給出 1,因為 last_insert_id() 僅使用原始表,而不使用觸發器表內部。

以上是相當於 MySQL 中的 SQL Server 函數 SCOPE_IDENTITY()?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除