5.2. Default Values
5.2.默认值
A column can be assigned a default value. When a new row is created and no values are specified for some of the columns, those columns will be filled with their respective default values. A data manipulation command can also request explicitly that a column be set to its default value, without having to know what that value is. (Details about data manipulation commands are in Chapter 6.)
可以为列分配默认值。当插入一行数据时,如果没有为某些列指定数据,则这些列可以自动的分别用各自的默认值填充。一条数据操作命令可以在不必知道某一列的默认值的情况下,显式将改列的值指定为其默认值。(有关数据操作命令的详情,请参见第6章。)
 
If no default value is declared explicitly, the default value is the null value. This usually makes sense because a null value can be considered to represent unknown data.
如果没有显式的指定默认值,那么默认值的默认值为null。因为null表示的是未知数据,这在理论上是讲得通的。
 
In a table definition, default values are listed after the column data type. For example:
在表定义中,默认值位于列数据类型之后。例如:
 
CREATE TABLE products (
product_no integer,
name text,
price numeric DEFAULT 9.99
);
 
The default value can be an expression, which will be evaluated whenever the default value is inserted (not when the table is created). A common example is for a timestamp column to have a default of  CURRENT_TIMESTAMP, so that it gets set to the time of row insertion. Another common example is generating a “serial number” for each row. In PostgreSQL this is typically done by something like:
默认值可以是一个表达式,它在默认值插入时进行计算(而不是在表创建时)。一个常用的示例是将具有timestamp数据类型的列的默认值设置为CURRENT_TIMESTAMP,以将其设置为列插入时的时间。另一个常用的示例是为每行生成一个***。在PostgreSQL中,可通过如下实现:
 
CREATE TABLE products (
product_no integer DEFAULT nextval('products_product_no_seq'),
...
);
where the nextval() function supplies successive values from a sequence object (see Section 9.16).
nextval()函数提供来自序列对象的连续值(参见9.16节)。
 
This arrangement is sufficiently common that there's a special shorthand for it:
上例写法比较普通,此处有个比较特殊的缩写:
 
CREATE TABLE products (
product_no SERIAL,
...
);
The SERIAL shorthand is discussed further in Section 8.1.4.
SERIAL缩写在第8.1.4节详细探讨。
 
测试:
记得Oracle的表定义中,默认值不能用序列:
5.2. Default Values
Oracle中:
5.2. Default Values
 

相关文章: