开发者

How do you make a field always default to a value in mySQL?

开发者 https://www.devze.com 2023-04-04 10:15 出处:网络
I have a text field (column). Every time I create a reco开发者_开发问答rd I want this particular column, called "type", to default to "FC" for every new record.

I have a text field (column).

Every time I create a reco开发者_开发问答rd I want this particular column, called "type", to default to "FC" for every new record.

I can't get it to work.

How do you make a field always default to a value in mySQL?


Try this after your create table statement:

ALTER TABLE TableName MODIFY type columnType Default 'FC';

That way, every time you insert a new row, type will have the value 'FC' unless otherwise specified.


Is your query inserting that column as a blank value? if so, that is probably the problem.


The only sollution I can think of is a trigger

A quick untested example from the manual and from the top of my head:

  CREATE TRIGGER ins_yourtable AFTER INSERT ON yourtable
->FOR EACH ROW SET type = 'FC';

If you can control all inserts you can also just skip the column while inserting: they you'll get the default value. But when the value is filled with someting (even '') it will get that value, so you're not forcing it.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号