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

前端 未结 2 1679
無奈伤痛
無奈伤痛 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

    0 讨论(0)
  • 2021-01-18 12:49

    But a Check Constraint will just check your entries and not put a default value. This is my exact same problem. However, I researched that a Calculated Column will do the trick.

    0 讨论(0)
提交回复
热议问题