Tuesday, August 21, 2012

a better cleaner/clearer post on auto-populating uniqueidentifiers in MSSQL

BEGIN TRANSACTION
GO
CREATE TABLE CarPart
   (
   CarPartId uniqueidentifier NOT NULL DEFAULT newid(),
   DescriptionOfObject varchar(255) NOT NULL,
   Price decimal(6,2) NOT NULL,
   AcquiredUpon datetime NOT NULL,
   SoldUpon datetime NULL
   )
GO
ALTER TABLE CarPart ADD CONSTRAINT
   PK_CarPart PRIMARY KEY CLUSTERED
   (
   CarPartId
   ) WITH( STATISTICS_NORECOMPUTE = OFF,
      IGNORE_DUP_KEY = OFF,
      ALLOW_ROW_LOCKS = ON,
      ALLOW_PAGE_LOCKS = ON)
COMMIT

...will allow for guids to automatically be created for the uniqueidentifier column like so:

INSERT INTO CarPart (DescriptionOfObject, Price, AcquiredUpon) VALUES ('2008 Infiniti EX35 Alternator', 115.99, '2008-04-05 00:00:00.000')

No comments:

Post a Comment