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
If you want to keep naming your constraints (and you should), I don’t think we can reduce it below 2 statements:
Note, that I’ve added a name for the default constraint. Also, this ensures that new rows also have
idvalues assigned. As I said in my comment, it’s usually preferable to avoid having columns with values generated byNEWID()clustered – it leads to lots of fragmentation. If you want to avoid that, considerNEWSEQUENTIALID().If you don’t care about constraint names, you can do it as a single query: