Add default value to an existing column based on If Then Else sql server 2008

前端 未结 2 1681
無奈伤痛
無奈伤痛 2021-01-18 12:06

Is it possible to alter an existing column to accept a default value based on another column value?

For Eg:

Create table #Temp
(
    TempId int not n         


        
2条回答
  •  滥情空心
    2021-01-18 12:45

    You can do it via CHECK constraint,

    First you will have to create table,

     create table myTemp1(TempId int not null ,TransCode int,ReasonCode int);
    

    and then add the constraint as

    create table myTemp1(TempId int not null ,TransCode int,ReasonCode int);

    alter table myTemp1
    add constraint check_role CHECK(case when (TransCode = 1 AND ReasonCode = NULL)
                                    then 99 else ReasonCode end = ReasonCode);
    

    OR like

    alter table myTemp1
    add constraint check_role CHECK(ReasonCode = (case when (TransCode = 1 AND ReasonCode
                                    = NULL) then 99 else ReasonCode end = 1))
    

    demo at http://sqlfiddle.com/#!3/d633a/1

提交回复
热议问题