Wednesday, March 21, 2012

Default additional field to identity value?

I've got a record that has an identity column and secondary identifier that I need to have default to the same value as the identity column:

id int identity(1,1) not null ,
name varchar(20) not null default CAST($IDENTITY AS VARCHAR(20))

Problem is, using @.@.identity or scope_identity() as the default for name gives me the prior insert's identity value, not the current record's value. Using an AFTER trigger doesn't work because the initial insert fails due to the not null constraint, and using an INSTEAD OF trigger does not work because the identity value is not set on the inserted row.

Is there any way to set a not-null field on a record equal to the identity value assigned to the record?

There is no way to do this declaratively. You can use a computed column instead of a persisted column if the name column is just string representation of the identity value. Do you allow the name value to be modified later? If so then you will have to use a trigger to update the value and set default to 0 or -1.sql

No comments:

Post a Comment