简体   繁体   English

如何设置列的默认值?

[英]How do I set the default value for a column?

Note the table below. 请注意下表。 I am wanting to set the default value for the newly created BEST_SELLER column to "N" . 我想将新创建的BEST_SELLER列的默认值设置为"N"
How do I go about doing that? 我该怎么做呢?

Create Table Mystery
(Book_Code Char(4) Primary Key,
 Title Varchar2(40),
 Publisher_Code Char(2),
 Price Number(4,2))

Basic MySQL Alter Table command 基本的MySQL Alter Table命令

If the column doesn't exist: 如果列不存在:

alter table Mystery add column BEST_SELLER enum('N','Y') default 'N';

and if column exists: 如果列存在:

alter table Mystery alter column BEST_SELLER set default 'N';

I am adding a second answer because of your response to my first answer. 我正在添加第二个答案,因为您回复了我的第一个答案。 This answer applies since: 这个答案适用于:

  1. You are using Oracle, and 您正在使用Oracle,和
  2. You have already created the table, so you need to use "ALTER TABLE" syntax. 您已经创建了表,因此需要使用“ALTER TABLE”语法。

Please find enclosed the following: 请附上以下内容:

alter table
    mystery
modify
    BEST_SELLER char(1) DEFAULT 'N'

Please modify the type char(1) to whatever the column actually is. 请将类型char(1)修改为实际列。 After running this query to correct the table, you will need to issue a second query to update the existing rows, such as: 运行此查询以更正表后,您将需要发出第二个查询来更新现有行,例如:

UPDATE 
    mystery 
SET 
    BEST_SELLER = 'N' 
WHERE 
       BEST_SELLER = '' 
    OR BEST_SELLER IS NULL

Hope this helps. 希望这可以帮助。

If you added the column after the table was created you can do something similar with the alter statement. 如果在创建表后添加了列,则可以使用alter语句执行类似操作。

alter 改变

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

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