Search code examples
sql-serversql-server-2008-r2primary-keyuniqueidentifieralter

New uniqueidentifier on the go


I want to add a column for a table which would become a PRIMARY KEY and be of type uniqueidentifier. I have this, but I wonder if there is a faster (in fewer code lines) way?

ALTER TABLE [table] ADD [id] [uniqueidentifier] 
    DEFAULT('00000000-0000-0000-0000-000000000000') NOT NULL
GO    
UPDATE [table] SET [id] = NEWID()
GO    
ALTER TABLE [table] ADD CONSTRAINT [PK_table_id] PRIMARY KEY CLUSTERED 
GO

Solution

  • If you want to keep naming your constraints (and you should), I don't think we can reduce it below 2 statements:

    create table T (
        Col1 varchar(10) not null
    )
    go
    insert into T (Col1)
    values ('abc'),('def')
    go
    ALTER TABLE T ADD [id] [uniqueidentifier] constraint DF_T_id DEFAULT(NEWID()) NOT NULL
    GO
    ALTER TABLE T ADD constraint PK_T PRIMARY KEY CLUSTERED (id)
    go
    drop table T
    

    Note, that I've added a name for the default constraint. Also, this ensures that new rows also have id values assigned. As I said in my comment, it's usually preferable to avoid having columns with values generated by NEWID() clustered - it leads to lots of fragmentation. If you want to avoid that, consider NEWSEQUENTIALID().

    If you don't care about constraint names, you can do it as a single query:

    ALTER TABLE T ADD [id] [uniqueidentifier] DEFAULT(NEWID()) NOT NULL PRIMARY KEY CLUSTERED