How to set a default value for one column in SQL based on another column

后端 未结 8 772
耶瑟儿~
耶瑟儿~ 2021-01-02 00:12

I\'m working with an old SQL 2000 database and I don\'t have a whole lot of SQL experience under my belt. When a new row is added to one of my tables I need to assign a defa

8条回答
  •  醉话见心
    2021-01-02 00:47

    If what you are looking for is to define a column definition based on another column you can do something like this:

    create table testable 
    (
        c1 int, 
        c2 datetime default getdate(), 
        c3 as year(c2)
    );
    
    insert into testable (c1) select 1
    
    select * from testable;
    

    Your result set should look like this :

    c1 | c2                      | c3
    1  | 2013-04-03 17:18:43.897 | 2013
    

    As you can see AS (in the column definition) does the trick ;) Hope it helped.

提交回复
热议问题