Wednesday, January 09, 2008
« T-SQL Performance With INNER JOINs | Main | Converting Legacy Tables From Int Primar... »

When you start to use GUIDs (uniqueidentifiers) as primary keys in T-SQL one of the first questions is how to replace @@IDENITY in your primary key column.  A typical table with int as a primary key might look like this:

CREATE T1(ID int PRIMARY KEY IDENTITY, Name varchar(50))

When you insert into this table and want the primary key of the row that you inserted you typically do this:

DECLARE @ID int

INSERT INTO T1 (Name) values ('Tom Smith')

SET @ID = @@IDENTITY

However, when you use uniqueidentifiers as primary keys you don't declare them as IDENTITY, here is how you would build this table:

CREATE T1(ID uniqueidentifier PRIMARY KEY , Name varchar(50))

And here is what the INSERT looks like:

DECLARE @Id uniqueidentifier

SET @Id = NewId()

INSERT INTO T1 (ID, Name) VALUES (@Id, 'Tom Smith')

When using uniqueidentifiers you create them ahead of the insertion and SQL Server doesn't keep track of the process for you.

{6230289B-5BEE-409e-932A-2F01FA407A92}

T-SQL | Wayne
Monday, January 07, 2008 12:47:26 PM (Pacific Standard Time, UTC-08:00)
I do this in C# when wanting to track GUID's. I usually add a bool parameter called "addingNew" or something similar to my constructors. So it'd be:

Foo foo = new Foo(true);

in my object:

public Foo(bool addingNew)
{
if (addingNew)
{
_fooId = Guid.NewGuid();
_createDate = DateTime.UtcNow;
}
}

This way if I want easy access to FooId I know exactly what it is without having to requery the database.
Name
E-mail
Home page

Comment (HTML not allowed)  

Enter the code shown (prevents robots):

Live Comment Preview