Is it possible to assign to a UNIQUEIDENTIFIER field automatically in each insertion?
I have a table in which I have an INT IDENTITY(1,1) PRIMARY KEY field, and right next to it an UNIQUEIDENTIFIER field which I would like to be automatically assigned upon each insertion on the table. I tried setting DEFAULT NEWID(), but it only works i开发者_运维百科f I do INSERT INTO TableName VALUES (DEFAULT, a, b, c, d, ...).
What I would like would be to be able to do INSERT INTO TableName VALUES (a, b, c, d, ...)
and the UNIQUEIDENTIFIER field be automatically assigned just like the primary key field. Is that possible? Please not that, although it is a valid thing to do, I don't want to have this field as (part of a) primary key for the table.
Use column list then and omit the PK, GUID columns
INSERT INTO TableName (col3, col4, col5, ...)
VALUES (a, b, c, d, ...) a
Using DEFAULT works around lack of column list which is best practice anyway. For example, what if you reorder or add columns? And using a trigger isn't optimal or scalable
Edit: Using a trigger is a workaround to avoid best practice... and won't scale too well
gbn is right. I'll just add a couple of other points you need to consider.
If you have a unique ID on your table, then why would you want or need a UNIQUEIDENTIFIER? You should probably choose one or the other as your PK, but not both. Also, when choosing a default for the database, choose NEWSEQUENTIALID() instead of NEWID().
It should be the Default value in the table schema. So you do not need to bother about this column after setting the default value.
Open the table design window and select the column which is supposed to occupy the GUID information. For more information, Please see below the screen shot.
So, by setting the (newID()) as a default value will let you insert the record without incorporating this column name in your insert statement.
Please let me know in case of any confusion
精彩评论