检索记录的uniqueidentifier键值 [英] Retrieve the uniqueidentifier key value for a record

查看:114
本文介绍了检索记录的uniqueidentifier键值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在SQL Server 2005的上下文中,我有一个表,其主键是一个uniqueidentifier(GUID),具有由newid()函数生成的默认值。我想编写一个将新记录插入表中的存储过程。如何获取记录的PK值?对于标识声明的字段,这很容易 - 我调用scope_identity()。我应该如何处理guids?



谢谢,
Lucian

解决方案>

我将在插入记录之前生成一个新的Guid,并明确使用这个新的Guid作为记录的PK。然后在插入之后使用该guid,知道它引用刚刚插入的行,例如

  DECLARE @newGuid uniqueidentifier 
SET @newGuid = newid()

INSERT INTO myTable(id,stringval)
VALUES(@newGuid,Hello)

SELECT * FROM myTable
WHERE id = @newGuid


in context of SQL Server 2005, I have a table for which the primary key is a uniqueidentifier (GUID), with a default value generated by the newid() function. I want to write a stored procedure that inserts a new record into the table. How do I get the record's PK value? for an identity-declared field, this is easy - I call scope_identity(). How should I proceed with guids?

Thanks, Lucian

解决方案

I would generate a new Guid prior to inserting the record, and explicitly use this new Guid as the PK for the record. You then use that guid after the insert, knowing that it refers to the row you have just inserted, e.g.

DECLARE @newGuid uniqueidentifier
SET @newGuid = newid()

INSERT INTO myTable(id, stringval)
VALUES (@newGuid, "Hello")

SELECT * FROM myTable
WHERE id = @newGuid

这篇关于检索记录的uniqueidentifier键值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆