获取插入行的 PK Guid 的最佳方法

发布于 2024-07-18 04:20:39 字数 317 浏览 9 评论 0原文

我读过这个问题关于获取插入的行。 我的问题有点相关。

有没有办法获取插入行的 guid? 我正在使用的表有一个 guid 作为主键(默认为 newid),我想在插入行后检索该 guid。

Guid 有类似 @@IDENTITYIDENT_CURRENTSCOPE_IDENTITY 的东西吗?

I've read this question about getting the identity of an inserted row. My question is sort of related.

Is there a way to get the guid for an inserted row? The table I am working with has a guid as the primary key (defaulted to newid), and I would like to retrieve that guid after inserting the row.

Is there anything like @@IDENTITY, IDENT_CURRENT or SCOPE_IDENTITY for Guids?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

情话墙 2024-07-25 04:20:39

您可以使用 OUTPUT 功能将默认值返回到参数中。

CREATE TABLE MyTable
(
    MyPK UNIQUEIDENTIFIER DEFAULT NEWID(),
    MyColumn1 NVARCHAR(100),
    MyColumn2 NVARCHAR(100)
)

DECLARE @myNewPKTable TABLE (myNewPK UNIQUEIDENTIFIER)

INSERT INTO 
    MyTable
(
    MyColumn1,
    MyColumn2
)
OUTPUT INSERTED.MyPK INTO @myNewPKTable
VALUES
(
    'MyValue1',
    'MyValue2'
)

SELECT * FROM @myNewPKTable

但我不得不说,使用唯一标识符作为主键时要小心。 对 GUID 进行索引的性能极差,因为任何新生成的 guid 都必须插入到索引的中间,而很少只是添加到末尾。 SQL2005 中有 NewSequentialId() 的新功能。 如果您的指南不需要模糊,那么它是一个可能的替代方案。

You can use the OUTPUT functionality to return the default values back into a parameter.

CREATE TABLE MyTable
(
    MyPK UNIQUEIDENTIFIER DEFAULT NEWID(),
    MyColumn1 NVARCHAR(100),
    MyColumn2 NVARCHAR(100)
)

DECLARE @myNewPKTable TABLE (myNewPK UNIQUEIDENTIFIER)

INSERT INTO 
    MyTable
(
    MyColumn1,
    MyColumn2
)
OUTPUT INSERTED.MyPK INTO @myNewPKTable
VALUES
(
    'MyValue1',
    'MyValue2'
)

SELECT * FROM @myNewPKTable

I have to say though, be careful using a unique identifier as a primary key. Indexing on a GUID is extremely poor performance as any newly generated guids will have to be inserted into the middle of an index and rrarely just added on the end. There is new functionality in SQL2005 for NewSequentialId(). If obscurity is not required with your Guids then its a possible alternative.

时光暖心i 2024-07-25 04:20:39

另一种更干净的方法,如果插入一行

CREATE TABLE MyTable
(
    MyPK UNIQUEIDENTIFIER DEFAULT NEWID(),
    MyColumn1 NVARCHAR(100),
    MyColumn2 NVARCHAR(100)
)

DECLARE @MyID UNIQUEIDENTIFIER;
SET @MyID = NEWID();

INSERT INTO 
    MyTable
(
    MyPK
    MyColumn1,
    MyColumn2
)
VALUES
(
    @MyID,
    'MyValue1',
    'MyValue2'
)

SELECT @MyID;

Another cleaner approach, if inserting a single row

CREATE TABLE MyTable
(
    MyPK UNIQUEIDENTIFIER DEFAULT NEWID(),
    MyColumn1 NVARCHAR(100),
    MyColumn2 NVARCHAR(100)
)

DECLARE @MyID UNIQUEIDENTIFIER;
SET @MyID = NEWID();

INSERT INTO 
    MyTable
(
    MyPK
    MyColumn1,
    MyColumn2
)
VALUES
(
    @MyID,
    'MyValue1',
    'MyValue2'
)

SELECT @MyID;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文