问题描述
我已阅读有关此问题的问题插入行的标识.我的问题有点相关.
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.
对于Guid,是否有@@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的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!