Sei sulla pagina 1di 1

Chapter 1: Creating 21

1.8.5 Expressions as Defaults


Some limited forms of function calls and expressions are allowed as DEFAULT
values. Unlike computed columns, these expressions are evaluated only once
when the row is inserted. Also, they cannot refer to any database objects no
columns or user-defined functions just literal values and built-in functions
with literal values as parameters.
<constant_function_call> ::= a built-in function call that does not reference
database objects
<constant_expression> ::= an expression that does not reference database objects
Here are some examples:
CREATE TABLE t (
c1 INTEGER,
server VARCHAR ( 100 ) DEFAULT PROPERTY ( 'MachineName' ),
today VARCHAR ( 100 ) DEFAULT DAYNAME ( CURRENT DATE ),
tomorrow DATE DEFAULT ( CURRENT DATE + 1 ),
guid BINARY ( 16 ) DEFAULT NEWID() );
The t.server column will be initialized to the machine name or IP address of the
computer running the server. The t.today column defaults to the day name of the
current date (e.g., 'Thursday'). The t.tomorrow column is initialized by adding 1
(day) to the CURRENT DATE.
The initial value for t.guid is a globally unique identifier, which looks like
'28c47c41-9cb8-11d7-88d6-0000863a7c57' when formatted via the
UUIDTOSTR() function.

Tip: The NEWID() default can be used instead of DEFAULT GLOBAL


AUTOINCREMENT when you cant assign a unique value to the
GLOBAL_DATABASE_ID option. The resulting values might not make the most
efficient primary key index but they are guaranteed to be globally unique with no
additional programming effort.

1.9 NULL Property


The NULL property is a declaration that this column may contain NULL values.
This is true by default for all columns unless the NOT NULL constraint is used,
with one exception: BIT columns are NOT NULL by default so you must use
the NULL property if you want a BIT column to be nullable.
NULL and DEFAULT NULL are two different things. NULL says you may
explicitly assign a NULL value to this column when the row is inserted or
updated, whereas DEFAULT NULL says this column will be assigned a NULL
value when the row is inserted unless you explicitly provide a different value.

1.10 Column Constraints


A column constraint is a rule about which values may be stored in a column.
They are coded as assertions about validity and they are evaluated at run time as
rows are inserted, updated, and deleted. Whenever a constraint fails (evaluates
as FALSE) one of two things happens: In most cases an error message is pro-
duced and the offending operation is cancelled, and in some cases the data is

Potrebbero piacerti anche