简体   繁体   中英

Generate new GUID in SQL Server if one is not provided

I am updating my database to have a column for a GUID for each record in a table.

This table is populated by several different sources and some of them will not provide a GUID for new records.

How can I populate this column with a newid() on the DB side only if there was no value passed in for a new record?

DO NOT I REPEAT DO NOT PLACE A DEFAULT COLUMN OF NEWID() . If you do the GUID you get will be completely random and if you have any sort of indexing on this column it will be useless. If you are going to do this you want to set the column default to be NEWSEQUENTIALID ( )

Kimberly Tripp has a Great Article and another Great Article on this subject.

To implement NEWSEQUENTIALID ( ) as a default:

CREATE TABLE foo
(unq_id UNIQUEIDENTIFIER DEFAULT NEWSEQUENTIALID(),
 cola varchar(10));

Full SQL Fiddle example. .

You can set the default value for the column to NEWID() . Then a GUID will be created and assigned only if one hasn't already been.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM