Tuesday, March 27, 2012

Default field to another field value on db level

Hi All,

I need to create a new field on a table and have that field default to another field value in that same table. Is there a way to do this w/ a default constraint rather than adding a trigger to the table? If i can't use a default constraint does anyone have a template trigger i could use? Below is an example of what i'm trying to do (Field_C is the new field and i want it to use Field_A value if no other value is specified on insert). Any help would be greatly appreciated.

alter table FOO add Field_C varchar(50) not null constraint FOO_default DEFAULT Field_A

thanks,
Davethis worked for me.....

CREATE Trigger TRG_FOO_default_INS
on dbo.FOO
for Insert
as

Declare @.default_FieldC varchar(50)

select @.default_FieldC = Field_C from inserted

If (@.default_FieldC is null) or (@.default_FieldC = '')
BEGIN
Update FOO set Field_C = Field_A where PK_ID in (select PK_ID from inserted)
END -- update externalname

No comments:

Post a Comment