Best way to get PK Guid of inserted row(获取插入行的 PK Guid 的最佳方法)
问题描述
我已阅读关于获取插入行的标识.我的问题有点相关.
I've read this question about getting the identity of an inserted row. My question is sort of related.
有没有办法获取插入行的 guid?我正在使用的表有一个 guid 作为主键(默认为 newid),我想在插入行后检索该 guid.
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.
Guids 是否有 @@IDENTITY
、IDENT_CURRENT
或 SCOPE_IDENTITY
之类的东西?
Is there anything like @@IDENTITY
, IDENT_CURRENT
or SCOPE_IDENTITY
for Guids?
推荐答案
您可以使用 OUTPUT 功能将默认值返回到参数中.
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
我不得不说,使用唯一标识符作为主键时要小心.对 GUID 进行索引的性能极差,因为任何新生成的 guid 都必须插入到索引的中间,并且很少只添加到最后.SQL2005 中有NewSequentialId() 的新功能.如果您的 Guid 不需要晦涩难懂,那么它是一种可能的替代方案.
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.
这篇关于获取插入行的 PK Guid 的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:获取插入行的 PK Guid 的最佳方法


- 更改自动增量起始编号? 2021-01-01
- 远程 mySQL 连接抛出“无法使用旧的不安全身份验证连接到 MySQL 4.1+"来自 XAMPP 的错误 2022-01-01
- 导入具有可变标题的 Excel 文件 2021-01-01
- 如何将 SonarQube 6.7 从 MySQL 迁移到 postgresql 2022-01-01
- 如何将 Byte[] 插入 SQL Server VARBINARY 列 2021-01-01
- 在SQL中,如何为每个组选择前2行 2021-01-01
- SQL 临时表问题 2022-01-01
- 以一个值为轴心,但将一行上的数据按另一行分组? 2022-01-01
- 使用 Oracle PL/SQL developer 生成测试数据 2021-01-01
- 如何使用 pip 安装 Python MySQLdb 模块? 2021-01-01