简体   繁体   English

如何为列添加默认值?

[英]How to add default value for a column?

I want to add the column Season ID to the Team table with the default referencing the None value in the Season table (I don't want to say default = 'None', rather the SeasonID of the row that has 'None' as the Season Year), place a foreign key constraint on that column. 我想将“季节ID”列添加到“团队”表中,并使用默认值引用“季节”表中的“无”值(我不想说默认值=“ None”,而是将“ None”作为行的SeasonID季节年份),在该列上放置外键约束。 Finally I need to add the Fall 2012 foreign key value into the Season ID column. 最后,我需要将2012年秋季外键值添加到Season ID列中。

Here is my team table 这是我的团队表

teamID      teamName
----------- ---------------
100         No Winner      
101         Purple Pilots  
102         Red Devils     
103         Silver Lions   
104         Blue Jackets   
105         Green Hornets  
106         Gold Dragons   

Here is my Season table 这是我的季节表

SeasonID    SeasonName Year
----------- ---------- ----
100         None       0000
101         Fall       2012
102         Winter     2012

Here is what i tried to do but I can handle the referencing for another table as for default value 这是我尝试做的事情,但我可以处理另一个表的引用作为默认值

alter table team
add SeasonID int not null;

alter table team
add default 'None'
for SeasonID

alter table team
add constraint team_seasonid_fk foreign key (SeasonID)
references Season(SeasonID)
on update cascade
on delete cascade;


update team
set SeasonID = 101
where SeasonID = 'None';

How can I do it correctly? 如何正确执行?

Your column is of type int so you cant assign 'none' as it's default value. 您的列的类型为int因此您不能将“ none”指定为默认值。 I suggest you to have a trigger on table and after insert find the default record from Season table and update the inserted record, or writing instead of insert trigger to do it at once. 我建议您在表上使用触发器,然后在插入后从Season表中查找默认记录并更新插入的记录,或者立即写instead of insert trigger来执行此操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM