DEV Community

Cover image for [MSSQL] SQL 新增完成後取得 PK
FakeStandard
FakeStandard

Posted on • Edited on

1

[MSSQL] SQL 新增完成後取得 PK

一開始學習 SQL 語法時不外乎是 CRUD,由於需求的關係,要將新增後產生的 PK 傳回到後端,或者是將 PK 拿去處理別的事,如果經驗值不夠或者還沒深入進階實務,會直覺地使用 SELECT 加上 ORDER BY 或者是 MAX 去找最後一筆資料:

-- 新增一筆資料
INSERT INTO Member (Name) VALUES('TEST')

-- 使用 MAX 找最大 PK
SELECT MAX(PK) FROM Member

-- 使用 ORDER BY 找出最後一筆資料
SELECT TOP 1 PK FROM Member ORDER BY PK DESC
Enter fullscreen mode Exit fullscreen mode

我們應該直接使用內建函數—@@IDENTITY傳回最後插入的識別值,該方法只能傳回識別種子。

INSERT INTO Member (Name) VALUES ('TEST')

-- 使用內建函數 @@IDENTITY
SELECT @@IDENTITY PK
Enter fullscreen mode Exit fullscreen mode

還有一種方法可以查看最後插入的識別種子,還可以任意查看指定欄位最後插入的值。

INSERT INTO Member (NAME)
-- 使用 OUTPUT 和 INSERTED 傳回指定的欄位
OUTPUT INSERTED.ID, INSERTED.Name
VALUES ('TEST')
Enter fullscreen mode Exit fullscreen mode

筆記

  • 第一種方法在時間差的情況下,會有小機率取得下一個使用者新增的 PK,故要取回自己新增資料的 PK ,此方法不適用。
  • 第二種方法比起第一種方法相對好很多,但它僅能傳回 PK。
  • 第三種方法應該是最安全及正規的作法,除了 PK 之外,還能查看其餘欄位的值。

Thanks for reading the article 🌷 🌻 🌼

If you like it, please don't hesitate to click heart button ❤️
or follow my GitHub ⭐ I'd appreciate it.


Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay