CREATE TABLE – SQL Command

 

CREATE TABLE – SQL Command

Creates a table having the specified fields.

CREATE TABLE | DBF TableName1 [NAME LongTableName] [FREE]   
(FieldName1 FieldType [(nFieldWidth [, nPrecision])]      
[NULL | NOT NULL]       [CHECK lExpression1 [ERROR cMessageText1]]      
[DEFAULT eExpression1]      [PRIMARY KEY | UNIQUE]      
[REFERENCES TableName2 [TAG TagName1]]      [NOCPTRANS]   
[, FieldName2 ...]      [, PRIMARY KEY eExpression2 TAG TagName2      
|, UNIQUE eExpression3 TAG TagName3]      
[, FOREIGN KEY eExpression4 TAG TagName4 [NODUP]         REFERENCES TableName3 [TAG TagName5]]      
[, CHECK lExpression2 [ERROR cMessageText2]])| FROM ARRAY ArrayName
Parameters
TableName1
Specifies the name of the table to create. The TABLE and DBF options are identical.
NAME LongTableName
Specifies a long name for the table. A long table name can be specified only when a database is open because long table names are stored in databases.

Long names can contain up to 128 characters and can be used in place of short file names in the database.

FREE
Specifies that the table will not be added to an open database. FREE isn't required if a database isn't open.
(FieldName1 FieldType [( nFieldWidth [, nPrecision])]
Specifies the field name, field type, field width, and field precision (number of decimal places), respectively.

A single table can contain up to 255 fields. If one or more fields allow null values, the limit is reduced by one to 254 fields.

FieldType is a single letter indicating the field's data type. Some field data types require that you specify nFieldWidth or nPrecision, or both.

The following table lists the values for FieldType and whether nFieldWidth and nPrecision are required.

FieldTypenFieldWidth nPrecisionDescription
CnCharacter field of width n
DDate
TDateTime
NndNumeric field of width n with d decimal places
FndFloating numeric field of width n with d decimal places
IInteger
BdDouble
YCurrency
LLogical
MMemo
GGeneral

nFieldWidth and nPrecision are ignored for D, T, I, Y, L, M, G, and P types. nPrecision defaults to zero (no decimal places) if nPrecision isn't included for the N or F types. nPrecision defaults to the number of decimal places specified by the SET DECIMAL setting if nPrecision isn't included for the B type.

NULL
Allows null values in the field. If one or more fields can contain null values, the maximum number of fields the table can contain is reduced by one, from 255 to 254.
NOT NULL
Prevents null values in the field.

If you omit NULL and NOT NULL, the current setting of SET NULL determines if null values are allowed in the field. However, if you omit NULL and NOT NULL and include the PRIMARY KEY or UNIQUE clause, the current setting of SET NULL is ignored and the field defaults to NOT NULL.

CHECK lExpression1
Specifies a validation rule for the field. lExpression1 can be a user-defined function. Note that when a blank record is appended, the validation rule is checked. An error is generated if the validation rule doesn't allow for a blank field value in an appended record.
ERROR cMessageText1
Specifies the error message Visual FoxPro displays when the validation rule specified with CHECK generates an error. The message is displayed only when data is changed within a Browse window or Edit window.
DEFAULT eExpression1
Specifies a default value for the field. The data type of eExpression1must be the same as the field's data type.
PRIMARY KEY
Creates a primary index for the field. The primary index tag has the same name as the field.
UNIQUE
Creates a candidate index for the field. The candidate index tag has the same name as the field. For more information about candidate indexes, see Setting a Primary or Candidate Index.
Note   Candidate indexes (created by including the UNIQUE option in CREATE TABLE or ALTER TABLE – SQL) are not the same as indexes created with the UNIQUE option in the INDEX command. An index created with the UNIQUE option in the INDEX command allows duplicate index keys; candidate indexes do not allow duplicate index keys. See INDEX for additional information on its UNIQUE option.

Null values and duplicate records are not permitted in a field used for a primary or candidate index. However, Visual FoxPro will not generate an error if you create a primary or candidate index for a field that supports null values. Visual FoxPro will generate an error if you attempt to enter a null or duplicate value into a field used for a primary or candidate index.

REFERENCES TableName2 [TAG TagName1]
Specifies the parent table to which a persistent relationship is established. If you omit TAG TagName1, the relationship is established using the primary index key of the parent table. If the parent table does not have a primary index, Visual FoxPro generates an error.

Include TAG TagName1 to establish a relation based on an existing index tag for the parent table. Index tag names can contain up to 10 characters.

The parent table cannot be a free table.

NOCPTRANS
Prevents translation to a different code page for character and memo fields. If the table is converted to another code page, the fields for which NOCPTRANS has been specified are not translated. NOCPTRANS can only be specified for character and memo fields. This will create what appears in the Table Designer as Character (binary) and Memo (binary) data types.

The following example creates a table named MYTABLE containing two character fields and two memo fields. The second character field CHAR2 and the second memo field MEMO2 include NOCPTRANS to prevent translation.

CREATE TABLE mytable (char1 C(10), char2 C(10) NOCPTRANS,;
   memo1 M, memo2 M NOCPTRANS)
PRIMARY KEY eExpression2 TAG TagName2
Specifies a primary index to create. eExpression2 specifies any field or combination of fields in the table. TAG TagName2 specifies the name for the primary index tag that is created. Index tag names can contain up to 10 characters.

Because a table can have only one primary index, you cannot include this clause if you have already created a primary index for a field. Visual FoxPro generates an error if you include more than one PRIMARY KEY clause in CREATE TABLE.

UNIQUE eExpression3 TAG TagName3
Creates a candidate index. eExpression3 specifies any field or combination of fields in the table. However, if you have created a primary index with one of the PRIMARY KEY options, you cannot include the field that was specified for the primary index. TAG TagName3 specifies a tag name for the candidate index tag that is created. Index tag names can contain up to 10 characters.

A table can have multiple candidate indexes.

FOREIGN KEY eExpression4 TAG TagName4 [NODUP]
Creates a foreign (non-primary) index, and establishes a relationship to a parent table. eExpression4 specifies the foreign index key expression and TagName4 specifies the name of the foreign index key tag that is created . Index tag names can contain up to 10 characters. Include NODUP to create a candidate foreign index.

You can create multiple foreign indexes for the table, but the foreign index expressions must specify different fields in the table.

REFERENCES TableName3 [TAG TagName5]
Specifies the parent table to which a persistent relationship is established. Include TAG TagName5 to establish a relation based on an index tag for the parent table. Index tag names can contain up to 10 characters. If you omit TAG TagName5, the relationship is established using the parent table's primary index key by default.
CHECK eExpression2 [ERROR cMessageText2]
Specifies the table validation rule. ERROR cMessageText2 specifies the error message Visual FoxPro displays when the table validation rule is executed. The message is displayed only when data is changed within a Browse window or Edit window.
FROM ARRAY ArrayName
Specifies the name of an existing array whose contents are the name, type, precision, and scale for each field in the table. The contents of the array can be defined with the AFIELDS( ) function.
Remarks

The new table is opened in the lowest available work area, and can be accessed by its alias. The new table is opened exclusively, regardless of the current setting of SET EXCLUSIVE.

If a database is open and you don't include the FREE clause, the new table is added to the database. You cannot create a new table with the same name as a table in the database.

If a database isn't open when you create the new table, including the NAME, CHECK, DEFAULT, FOREIGN KEY, PRIMARY KEY, or REFERENCES clauses generates an error.

Note that the CREATE TABLE syntax uses commas to separate certain CREATE TABLE options. Also, the NULL, NOT NULL, CHECK, DEFAULT, PRIMARY KEY and UNIQUE clause must be placed within the parentheses containing the column definitions.

Example

The following example creates a new database named Mydata1. CREATE TABLE is used to create three tables (Salesman, Customer, and Orders). The FOREIGN KEY and REFERENCES clauses in the second CREATE TABLE command create a persistent one-to-many relationship between the Salesman and Customer tables. The DEFAULT clauses in the third CREATE TABLE command establish default values, and the CHECK and ERROR clauses establish business rules for entering data into specific fields. The MODIFY DATABASE is used to display the relationship between the three tables.

CLOSE DATABASES
CLEAR

* Create mydata database in the current directory or folder
CREATE DATABASE mydata1

* Create a salesman table with a primary key
CREATE TABLE salesman ;
   (SalesID c(6) PRIMARY KEY, ;
   SaleName C(20))

* Create a customer table and relate it to the salesman table.
CREATE TABLE customer ;
   (SalesID c(6), ;
   CustId i PRIMARY KEY, ;
   CustName c(20) UNIQUE,   ;
   SalesBranch c(3), ;
   FOREIGN KEY SalesId TAG SalesId REFERENCES salesman)

* Create an orders table related to customer with its own primary
* key and some business rules such as defaults & checks.
CREATE TABLE orders ;
   (OrderId i PRIMARY KEY, ;
      CustId i REFERENCES customer TAG CustId, ;
      OrderAmt y(4), ;
      OrderQty i ;
      DEFAULT 10 ;
      CHECK (OrderQty > 9) ;
      ERROR "Order Quantity must be at least 10", ;
         DiscPercent n(6,2) NULL ;
      DEFAULT .NULL., ;
      CHECK (OrderAmt > 0) ERROR "Order Amount Must be > 0" )

* Display new database, tables, and relationships
MODIFY DATABASE

* Delete example files
SET SAFETY OFF && To suppress verification message
CLOSE DATABASES     && Close database before deleting
DELETE DATABASE mydata1 DELETETABLES
相关文章
对该文的评论
seapen ( 2002-04-01)
SQL的BOL(Books OnLine)也搬出来了 那篇评论倒不知出自何处?
S_C ( 2002-04-01)
CREATE TABLE------SQL Reference The CREATE TABLE statement defines a table. The definition must include its name and the names and attributes of its columns. The definition may include other attributes of the table, such as its primary key or check constraints.  Invocation  This statement can be embedded in an application program or issued through the use of dynamic SQL statements. It is an executable statement that can be dynamically prepared.  Authorization  The privileges held by the authorization ID of the statement must include at least one of the following:  SYSADM or DBADM authority  CREATETAB authority on the database and one of:  IMPLICIT_SCHEMA authority on the database, if the implicit or explicit schema name of the table does not exist  CREATEIN privilege on the schema, if the schema name of the table refers to an existing schema.  If a subtable is being defined, the authorization ID must be the same as the definer of the root table of the table hierarchy.  To define a foreign key, the privileges held by the authorization ID of the statement must include one of the following on the parent table:  REFERENCES privilege on the table  REFERENCES privilege on each column of the specified parent key  CONTROL privilege on the table  SYSADM or DBADM authority.  To define a summary table (using a fullselect) the privileges held by the authorization ID of the statement must include at least one of the following on each table or view identified in the fullselect:  SELECT privilege on the table or view and ALTER privilege if REFRESH DEFERRED or REFRESH IMMEDIATE is specified  CONTROL privilege on the table or view  SYSADM or DBADM authority.  Syntax  >>-CREATE--+----------+---TABLE--table-name--------------------->            '-SUMMARY--'   >-----+-| element-list |----------------------------------------------------+>       +-OF--type-name1--+-------------------+---+-------------------------+-+       |                 '-| under-clause |--'   '-| typed-element-list |--' |       '-| summary-table-definition |----------------------------------------'           .-DATA CAPTURE NONE----. >----*--+----------------------+--*----------------------------->         '-DATA CAPTURE CHANGES-'   >-----+-----------------------------------------------+--*------>       '-IN--tablespace-name1--| tablespace-options |--'   >-----+------------------------------------------------------------+>       |                   .-,---------------.                      |       |                   V                 |   .-USING HASHING--. |       +-PARTITIONING KEY-----(--column--)---+---+----------------+-+       '-REPLICATED-------------------------------------------------'   >----*--+----------------------+---*---------------------------><         '-NOT LOGGED INITIALLY-'   element-list          .-,---------------------------------.        V                                   | |---(------+-| column-definition |------+--+---)----------------|            +-| unique-constraint |------+            +-| referential-constraint |-+            '-| check-constraint |-------'   under-clause   |---UNDER--supertable-name--INHERIT SELECT PRIVILEGES-----------|   typed-element-list          .-,---------------------------------.        V                                   | |---(------+-| OID-column-definition |--+--+---)----------------|            +-| with-options |-----------+            +-| unique-constraint |------+            +-| referential-constraint |-+            '-| check-constraint |-------'     summary-table-definition   |--AS--(--fullselect--)--| summary-table-options |--------------|   summary-table-options   |---+-DEFINITION ONLY----------------------------------+--------|     '-DATA INITIALLY--DEFERRED--REFRESH--+-DEFERRED--+-'                                          '-IMMEDIATE-'     tablespace-options   |--+----------------------------------+------------------------->    |                            (1)   |    '-INDEX IN--tablespace-name2-------'   >-----+----------------------------+----------------------------|       '-LONG IN--tablespace-name3--'   column-definition   |---column-name----| data-type |--+---------------------+-------|                                   '-| column-options |--'   column-options       .---------------------------------------------------------------------------------.     V                                                                                 | |------+---------------------------------------------------------------------------+--+->        +-NOT NULL------------------------------------------------------------------+        +-| default-clause |--------------------------------------------------------+        |                 (2)                                                       |        +-| lob-options |-----------------------------------------------------------+        |                      (3)                                                  |        +-| datalink-options |------------------------------------------------------+        |                              (4)                                          |        +-SCOPE--+-typed-table-name-+-----------------------------------------------+        |        '-typed-view-name--'                                               |        '-+-----------------------------------+---+-+-PRIMARY KEY-+---------------+-'          |            (5)                    |   | '-UNIQUE------'               |          '-CONSTRAINT-------constraint-name--'   +-| references-clause |---------+                                                  '-CHECK--(--check-condition--)--'   >---------------------------------------------------------------|   Notes:  Specifying which table space will contain a table's index can only be done when the table is created.  The lob-options clause only applies to large object types (BLOB, CLOB and DBCLOB) and distinct types based on large object types.  The datalink-options clause only applies to the DATALINK type and distinct types based on the DATALINK type. The LINKTYPE URL clause is required for these types.  The SCOPE clause only applies to the REF type.  For compatibility with Version 1, the CONSTRAINT keyword may be omitted in a column-definition defining a references-clause.    data-type   |--+-SMALLINT-----------------------------------------------------------------------+->    +-+-INTEGER-+--------------------------------------------------------------------+    | '-INT-----'                                                                    |    +-BIGINT-------------------------------------------------------------------------+    +-+-FLOAT--+----------------+-+--------------------------------------------------+    | |        '-(--integer--)--' |                                                  |    | +-REAL----------------------+                                                  |    | |        .-PRECISION-.      |                                                  |    | '-DOUBLE-+-----------+------'                                                  |    +--+-DECIMAL-+---+--------------------------------+------------------------------+    |  +-DEC-----+   '-(--integer--+-----------+---)--'                              |    |  +-NUMERIC-+                 '-,integer--'                                     |    |  '-NUM-----'                                                                   |    +--+--+-CHARACTER-+---+------------+----------------+---+----------------------+-+    |  |  '-CHAR------'   '-(integer)--'                |   |  (1)                 | |    |  +--+-VARCHAR-------------------+--(--integer--)--+   '--------FOR BIT DATA--' |    |  |  '--+-CHARACTER-+---VARYING--'                 |                            |    |  |     '-CHAR------'                              |                            |    |  '-LONG VARCHAR-----------------------------------'                            |    |                                                                                |    +--+-BLOB---+--(--integer--+---+---)---------------------------------------------+    |  +-CLOB---+              +-K-+                                                 |    |  '-DBCLOB-'              +-M-+                                                 |    |                          '-G-'                                                 |    +-GRAPHIC--+------------+--------------------------------------------------------+    |          '-(integer)--'                                                        |    +-VARGRAPHIC--(integer)----------------------------------------------------------+    +-LONG VARGRAPHIC----------------------------------------------------------------+    +-DATE---------------------------------------------------------------------------+    +-TIME---------------------------------------------------------------------------+    +-TIMESTAMP----------------------------------------------------------------------+    +-DATALINK--+----------------+---------------------------------------------------+    |           '-(--integer--)--'                                                   |    +-distinct-type-name-------------------------------------------------------------+    '-REF--(type-name2)--------------------------------------------------------------'   >---------------------------------------------------------------|   Notes:  The FOR BIT DATA clause may be specified in random order with the other column constraints that follow.    default-clause      .-WITH-. |--+------+--DEFAULT--+---------------------+-------------------|                       '-| default-values |--'   default-values   |---+-constant---------------------------------------------+----|     +-datetime-special-register----------------------------+     +-USER-------------------------------------------------+     +-NULL-------------------------------------------------+     '-cast-function--(--+-constant------------------+---)--'                         +-datetime-special-register-+                         '-USER----------------------'   lob-options          .-LOGGED-----.      .-NOT COMPACT--. |---*--+------------+---*--+--------------+---*-----------------|        '-NOT LOGGED-'      '-COMPACT------'   datalink-options   |---LINKTYPE URL------------------------------------------------>        .-NO LINK CONTROL------------------------------. >----+----------------------------------------------+-----------|      '-FILE LINK CONTROL--+-| file-link-options |-+-'                           '-MODE DB2OPTIONS-------'   file-link-options   |---*--INTEGRITY----ALL----*--READ PERMISSION--+-FS-+----------->                                                '-DB-'   >----*--WRITE PERMISSION--+-FS------+--*--RECOVERY--+-NO--+----->                           '-BLOCKED-'               '-YES-'   >----*--ON UNLINK--+-RESTORE-+---*------------------------------|                    '-DELETE--'     references-clause   |--REFERENCES--table-name----+----------------------------+----->                              |    .-,--------------.      |                              |    V                |      |                              '-(-----column-name---+---)--'   >-----| rule-clause |-------------------------------------------|   rule-clause         .-ON DELETE NO ACTION-----.      .-ON UPDATE NO ACTION--. |--*--+-------------------------+---*--+----------------------+---*-->       '-ON DELETE--+-RESTRICT-+-'      '-ON UPDATE RESTRICT---'                    +-CASCADE--+                    '-SET NULL-'   >---------------------------------------------------------------|   unique-constraint   |---+------------------------------+---+-UNIQUE------+---------->     '-CONSTRAINT--constraint-name--'   '-PRIMARY KEY-'           .-,--------------.         V                | >----(-----column-name---+---)----------------------------------|   referential-constraint   |---+-----------------------------------+--FOREIGN KEY---------->     |                             (1)   |     '-CONSTRAINT--constraint-name-------'           .-,--------------.         V                | >----(-----column-name---+---)----| references-clause |---------|   check-constraint   |--+------------------------------+----------------------------->    '-CONSTRAINT--constraint-name--'   >----CHECK--(--check-condition--)-------------------------------|   OID-column-definition   |---REF IS--OID-column-name--USER GENERATED---------------------|   with-options   |---column-name--WITH OPTIONS---| column-options |--------------|   Notes:  For compatibility with Version 1, constraint-name may be specified following FOREIGN KEY (without the CONSTRAINT keyword).  Description  SUMMARY  Indicates that a summary table is being defined. The keyword is optional, but when specified, the statement must include a summary-table-definition.  table-name  Names the table. The name, including the implicit or explicit qualifier, must not identify a table, view, or alias described in the catalog. The schema name must not be SYSIBM, SYSCAT, SYSFUN, or SYSSTAT (SQLSTATE 42939).  OF type-name1  Specifies that the columns of the table are based on the attributes of the structured type identified by type-name1. If type-name1 is specified without a schema name, the type name is resolved by searching the schemas on the SQL path (defined by the FUNCPATH preprocessing option for static SQL and by the CURRENT PATH register for dynamic SQL). The type name must be the name of an existing user-defined type (SQLSTATE 42704) and it must be a structured type (SQLSTATE 428DP).  If UNDER is not specified, an object identifier column must be specified (refer to the OID-column-definition) as the first column of the table. The object ID column is followed by columns based on the attributes of type-name1.  UNDER supertable-name  Indicates that the table is a subtable of supertable-name. The supertable must be an existing table (SQLSTATE 42704) and the table must be defined using a structured type that is the immediate supertype of type-name1 (SQLSTATE 428DB). The schema name of table-name and supertable-name must be the same (SQLSTATE 428DQ). The table identified by supertable-name must not have any existing subtable already defined using type-name1 (SQLSTATE 42742).  The columns of the table include the object identifier column of the supertable with its type modified to be REF(type-name1), followed by columns based on the attributes of type-name1 (remember that the type includes the attributes of its supertype). The attribute names cannot be the same as the OID column name (SQLSTATE 42711).  Other table options including table space, data capture, not logged initially and partitioning key options cannot be specified. These options are inherited from the supertable (SQLSTATE 42613).  INHERIT SELECT PRIVILEGES  Any user or group holding a SELECT privilege on the supertable will be granted an equivalent privilege on the newly created subtable. The subtable definer is considered to be the grantor of this privilege.  element-list  Defines the elements of a table. This includes the definition of columns and constraints on the table.  typed-element-list  Defines the additional elements of a typed table. This includes the additional options for the columns, the addition of an object identifier column (root table only), and constraints on the table.  summary-table-definition  If the table definition is based on the result of a query, then the table is a summary table based on the query.  AS  Introduces the query that is used for the definition of the table or to determine the data included in the table.  fullselect  Defines the query in which the table is based. The summary-table-options specified define attributes of the summary table. The option chosen also defines the contents of the fullselect as follows:  Defines the query in which the table is based. The summary-table-options define attributes of the summary table. The option chosen also defines the contents of the fullselect as follows.  When REFRESH DEFERRED or REFRESH IMMEDIATE is specified, the fullselect cannot include:  references to a view, summary table, or typed table in any FROM clause  expressions that are a reference type or DATALINK type (or distinct type based on these types)  functions that have external action  functions that depend on physical characteristics (for example NODENUMBER, PARTITION)  table or view references to system objects (explain tables also should not be specified).  When REFRESH IMMEDIATE is specified, the fullselect must be a subselect and cannot include:  functions that are not deterministic  scalar fullselects  predicates with fullselects  special registers  DISTINCT in the SELECT clause  expression in the select list that are other than column names  FROM clause references other than to a single base table  GROUP BY clause and HAVING clause.  Furthermore, for REFRESH IMMEDIATE, the base table must have at least one unique index defined and the SELECT clause must include all of the columns of this unique index.  summary-table-options  Define the attributes of the summary table.  DEFINITION ONLY  Data is used to define the elements of the table. The table is not populated using the results of query and the REFRESH TABLE statement cannot be used. When the CREATE TABLE statement is completed, the table is no longer considered a summary table.  DATA INITIALLY DEFERRED  Data is not inserted into the table as part of the CREATE TABLE statement. A REFRESH TABLE statement specifying the table-name is used to insert data into the table.  REFRESH  Indicates how the data in the table is maintained.  DEFERRED  The data in the table can be refreshed at any time using the REFRESH TABLE statement. The data in the table only reflects the result of the query as a snapshot at the time the REFRESH TABLE statement is processed. Summary tables defined with this attribute do not allow INSERT, UPDATE or DELETE statements (SQLSTATE 42807).  IMMEDIATE  The changes made to the underlying tables as part of a DELETE, INSERT, or UPDATE are cascaded to the summary table. In this case, the content of the table, at any point-in-time, is the same as if the specified subselect is processed. Summary tables defined with this attribute do not allow INSERT, UPDATE, or DELETE statements (SQLSTATE 42807).  column-definition  Defines the attributes of a column.  column-name  Names a column of the table. The name cannot be qualified and the same name cannot be used for more than one column of the table.  A table may have the following:  a 4K page size with maximum of 500 columns where the byte counts of the columns must not be greater than 4005 in a 4K page size, or  an 8K page size with maximum of 1012 columns where the byte counts of the columns must not be greater than 8101.  data-type  Is one of the types in the following list. Use:  SMALLINT  For a small integer.  INTEGER  or  INT  For a large integer.  BIGINT  For a big integer.  FLOAT(integer)  For a single or double precision floating-point number, depending on the value of the integer. The value of the integer must be in the range 1 through 53. The values 1 through 24 indicate single precision and the values 25 through 53 indicate double precision.  You can also specify:  REAL  For single precision floating-point.  DOUBLE  For double precision floating-point.  DOUBLE PRECISION  For double precision floating-point.  FLOAT  For double precision floating-point.  DECIMAL(precision-integer, scale-integer)  or  DEC(precision-integer, scale-integer)  For a decimal number. The first integer is the precision of the number; that is, the total number of digits; it may range from 1 to 31. The second integer is the scale of the number; that is, the number of digits to the right of the decimal point; it may range from 0 to the precision of the number.  If precision and scale are not specified, the default values of 5,0 are used. The words NUMERIC and NUM can be used as synonyms for DECIMAL and DEC.  CHARACTER(integer)  or  CHAR(integer)  or  CHARACTER  or  CHAR  For a fixed-length character string of length integer, which may range from 1 to 254. If the length specification is omitted, a length of 1 character is assumed.  VARCHAR(integer),  or  CHARACTER VARYING(integer),  or  CHAR VARYING(integer)  For a varying-length character string of maximum length integer, which may range from 1 to 4000.  LONG VARCHAR  For a varying-length character string with a maximum length of 32700.  FOR BIT DATA  Specifies that the contents of the column are to be treated as bit (binary) data. During data exchange with other systems, code page conversions are not performed. Comparisons are done in binary, irrespective of the database collating sequence.  BLOB(integer [K | M | G])  For a binary large object string of the specified maximum length in bytes.  The length may be in the range of 1 byte to 2 147 483 647 bytes.  If integer by itself is specified, that is the maximum length.  If integer K (in either upper or lower case) is specified, the maximum length is 1 024 times integer. The maximum value for integer is 2 097 152.  If integer M is specified, the maximum length is 1 048 576 times integer. The maximum value for integer is 2 048.  If integer G is specified, the maximum length is 1 073 741 824 times integer. The maximum value for integer is 2.  To create BLOB strings greater than 1 gigabyte, you must specify the NOT LOGGED option.  Any number of spaces is allowed between the integer and K, M, or G. Also, no space is required. For example, all the following are valid.     BLOB(50K)    BLOB(50 K)    BLOB (50   K) CLOB(integer [K | M | G]) (61)  For a character large object string of the specified maximum length in bytes.  The meaning of the integer K | M | G is the same as for BLOB.  To create CLOB strings greater than 1 gigabyte, you must specify the NOT LOGGED option.  DBCLOB(integer [K | M | G])  For a double-byte character large object string of the specified maximum length in double-byte characters.  The meaning of the integer K | M | G is similar to that for BLOB. The differences are that the number specified is the number of double-byte characters and that the maximum size is 1 073 741 823 double-byte characters.  To create DBCLOB strings greater than 1 gigabyte, you must specify the NOT LOGGED option.  GRAPHIC(integer)  For a fixed-length graphic string of length integer which may range from 1 to 127. If the length specification is omitted, a length of 1 is assumed.  VARGRAPHIC(integer)  For a varying-length graphic string of maximum length integer, which may range from 1 to 2000.  LONG VARGRAPHIC  For a varying-length graphic string with a maximum length of 16350.  DATE  For a date.  TIME  For a time.  TIMESTAMP  For a timestamp.  DATALINK  or  DATALINK(integer)  For a link to data stored outside the database.  The column in the table consists of "anchor values" that contain the reference information that is required to establish and maintain the link to the external data as well as an optional comment.  The length of the column is 200. If the length specification is omitted, a length of 200 bytes is assumed.  A DATALINK value is an encapsulated value with a set of built-in scalar functions. There is a function called DLVALUE to create a DATALINK value. The following functions can be used to extract attributes from a DATALINK value.  DLCOMMENT  DLLINKTYPE  DLURLCOMPLETE  DLURLPATH  DLURLPATHONLY  DLURLSCHEME  DLURLSERVER  A DATALINK column has the following restrictions:  The column cannot be part of any index. Therefore, it cannot be included as a column of a primary key or unique constraint (SQLSTATE 42962).  The column cannot be a foreign key of a referential constraint (SQLSTATE 42830).  A default value (WITH DEFAULT) cannot be specified for the column. If the column is nullable, the default for the column is NULL (SQLSTATE 42894).  distinct-type-name  For a user-defined type that is a distinct type. If a distinct type name is specified without a schema name, the distinct type name is resolved by searching the schemas on the SQL path (defined by the FUNCPATH preprocessing option for static SQL and by the CURRENT PATH register for dynamic SQL).  If a column is defined using a distinct type, then the data type of the column is the distinct type. The length and the scale of the column are respectively the length and the scale of the source type of the distinct type.  If a column defined using a distinct type is a foreign key of a referential constraint, then the data type of the corresponding column of the primary key must have the same distinct type.  REF (type-name2)  For a reference to a typed table. If type-name2 is specified without a schema name, the type name is resolved by searching the schemas on the SQL path (defined by the FUNCPATH preprocessing option for static SQL and by the CURRENT PATH register for dynamic SQL). The underlying data type of the column is based on the data type VARCHAR(16) FOR BIT DATA.  column-options  Defines additional options related to columns of the table.  NOT NULL  Prevents the column from containing null values.  If NOT NULL is not specified, the column can contain null values, and its default value is either the null value or the value provided by the WITH DEFAULT clause.  default-clause  Specifies a default value for the column.  WITH  An optional keyword.  DEFAULT  Provides a default value in the event a value is not supplied on INSERT or is specified as DEFAULT on INSERT or UPDATE. If a default value is not specified following the DEFAULT keyword, the default value depends on the data type of the column as shown in Table 16.  If a column is defined as a DATALINK, then a default value cannot be specified. The only possible default is NULL.  If the column is based on an attribute of a structured type, a specific default value must be specified when defining a default.  If a column is defined using a distinct type, then the default value of the column is the default value of the source data type cast to the distinct type.  Omission of DEFAULT from a column-definition results in the use of the null value as the default for the column.  default-values  Specific types of default values that can be specified are as follows.  constant  Specifies the constant as the default value for the column. The specified constant must:  represent a value that could be assigned to the column in accordance with the rules of assignment as described in Chapter 3  not be a floating-point constant unless the column is defined with a floating-point data type  not have non-zero digits beyond the scale of the column data type if the constant is a decimal constant (for example, 1.234 cannot be the default for a DECIMAL(5,2) column)  be expressed with no more than 254 characters including the quote characters, any introducer character such as the X for a hexadecimal constant, and characters from the fully qualified function name and parentheses when the constant is the argument of a cast-function.  datetime-special-register  Specifies the value of the datetime special register (CURRENT DATE, CURRENT TIME, or CURRENT TIMESTAMP) at the time of INSERT or UPDATE as the default for the column. The data type of the column must be the data type that corresponds to the special register specified (for example, data type must be DATE when CURRENT DATE is specified).  USER  Specifies the value of the USER special register at the time of INSERT or UPDATE as the default for the column. If USER is specified, the data type of the column must be a character string with a length not less than the length attribute of USER.  NULL  Specifies NULL as the default for the column. If NOT NULL was specified, DEFAULT NULL may be specified within the same column definition but will result in an error on any attempt to set the column to the default value.  cast-function  This form of a default value can only be used with columns defined as a distinct type, BLOB or datetime (DATE, TIME or TIMESTAMP) data type. For distinct type, with the exception of distinct types based on BLOB or datetime types, the name of the function must match the name of the distinct type for the column. If qualified with a schema name, it must be the same as the schema name for the distinct type. If not qualified, the schema name from function resolution must be the same as the schema name for the distinct type. For a distinct type based on a datetime type, where the default value is a constant, a function must be used and the name of the function must match the name of the source type of the distinct type with an implicit or explicit schema name of SYSIBM. For other datetime columns, the corresponding datetime function may also be used. For a BLOB or a distinct type based on on BLOB, a function must be used and the name of the function must be BLOB with an implicit or explicit schema name of SYSIBM. An example using the cast-function is given in Example 8 on page ***.  constant  Specifies a constant as the argument. The constant must conform to the rules of a constant for the source type of the distinct type or for the data type if not a distinct type. If the cast-function is BLOB, the constant must be a string constant.  datetime-special-register  Specifies CURRENT DATE, CURRENT TIME, or CURRENT TIMESTAMP. The source type of the distinct type of the column must be the data type that corresponds to the specified special register.  USER  Specifies the USER special register. The data type of the source type of the distinct type of the column must be a string data type with a length of at least 8 bytes. If the cast-function is BLOB, the length attribute must be at least 8 bytes.  If the value specified is not valid, an error (SQLSTATE 42894) is raised.  lob-options  Specifies options for LOB data types.  LOGGED  Specifies that changes made to the column are to be written to the log. The data in such columns is then recoverable with database utilities (such as RESTORE DATABASE). LOGGED is the default.  LOBs greater than 1 gigabyte cannot be logged (SQLSTATE 42993) and LOBs greater than 10 megabytes should probably not be logged.  NOT LOGGED  Specifies that changes made to the column are not to be logged.  NOT LOGGED has no effect on a commit or rollback operation; that is, the database's consistency is maintained even if a transaction is rolled back, regardless of whether or not the LOB value is logged. The implication of not logging is that during a roll forward operation, after a backup or load operation, the LOB data will be replaced by zeros for those LOB values that would have had log records replayed during the roll forward. During crash recovery, all committed changes and changes rolled back will reflect the expected results. See the Administration Guide for the implications of not logging LOB columns.  COMPACT  Specifies that the values in the LOB column should take up minimal disk space (free any extra disk pages in the last group used by the LOB value), rather than leave any left-over space at the end of the LOB storage area that might facilitate subsequent append operations. Note that storing data in this way may cause a performance penalty in any append (length-increasing) operations on the column.  NOT COMPACT  Specifies some space for insertions to assist in future changes to the LOB values in the column. This is the default.  datalink-options  Specifies the options associated with a DATALINK data type.  LINKTYPE URL  This defines the type of link as a Uniform Resource Locator (URL).  NO LINK CONTROL  Specifies that there will not be any check made to determine that the file exists. Only the syntax of the URL will be checked. There is no database manager control over the file.  FILE LINK CONTROL  Specifies that a check should be made for the existence of the file. Additional options may be used to give the database manager further control over the file.  file-link-options  Additional options to define the level of database manager control of the file link.  INTEGRITY  Specifies the level of integrity of the link between a DATALINK value and the actual file.  ALL  Any file specified as a DATALINK value is under the control of the database manager and may NOT be deleted or renamed using standard file system programming interfaces.  READ PERMISSION  Specifies how permission to read the file specified in a DATALINK value is determined.  FS  The read access permission is determined by the file system permissions. Such files can be accessed without retrieving the file name from the column.  DB  The read access permission is determined by the database. Access to the file will only be allowed by passing a valid file access token, returned on retrieval of the DATALINK value from the table, in the open operation.  WRITE PERMISSION  Specifies how permission to write to the file specified in a DATALINK value is determined.  FS  The write access permission is determined by the file system permissions. Such files can be accessed without retrieving the file name from the column.  BLOCKED  Write access is blocked. The file cannot be directly updated through any interface. An alternative mechanism must be used to cause updates to the information. For example, the file is copied, the copy updated, and then the DATALINK value updated to point to the new copy of the file.  RECOVERY  Specifies whether or not DB2 will support point in time recovery of files referenced by values in this column.  YES  DB2 will support point in time recovery of files referenced by values in this column. This value can only be specified when INTEGRITY ALL and WRITE PERMISSION BLOCKED are also specified.  NO  Specifies that point in time recovery will not be supported.  ON UNLINK  Specifies the action taken on a file when a DATALINK value is changed or deleted (unlinked). Note that this is not applicable when WRITE PERMISSION FS is used.  RESTORE  Specifies that when a file is unlinked, the DataLink File Manager will attempt to return the file to the owner with the permissions that existed at the time the file was linked. In the case where the user is no longer registered with the file server, the result is product-specific. (62) This can only be specified when INTEGRITY ALL and WRITE PERMISSION BLOCKED are also specified.  DELETE  Specifies that the file will be deleted when it is unlinked. This can only be specified when READ PERMISSION DB and WRITE PERMISSION BLOCKED are also specified.  MODE DB2OPTIONS  This mode defines a set of default file link options. The defaults defined by DB2OPTIONS are:  INTEGRITY ALL  READ PERMISSION FS  WRITE PERMISSION FS  RECOVERY NO  ON UNLINK is not applicable since WRITE PERMISSION FS is used.  SCOPE  Identifies the scope of the reference type column.  A scope must be specified for any column that is intended to be used as the left operand of a dereference operator or as the argument of the DEREF function. Specifying the scope for a reference type column may be deferred to a subsequent ALTER TABLE statement to allow the target table to be defined, usually in the case of mutually referencing tables.  typed-table-name  The name of a typed table. The table must already exist or be the same as the name of the table being created (SQLSTATE 42704). The data type of column-name must be REF(S), where S is the type of typed-table-name (SQLSTATE 428DM). No checking is done of values assigned to column-name to ensure that the values actually reference existing rows in typed-table-name.  typed-view-name  The name of a typed view. The view must already exist or be the same as the name of the view being created (SQLSTATE 42704). The data type of column-name must be REF(S), where S is the type of typed-view-name (SQLSTATE 428DM). No checking is done of values assigned to column-name to ensure that the values actually reference existing rows in typed-view-name.  CONSTRAINT constraint-name  Names the constraint. A constraint-name must not identify a constraint that was already specified within the same CREATE TABLE statement. (SQLSTATE 42710).  If this clause is omitted, an 18-character identifier unique within the identifiers of the existing constraints defined on the table, is generated (63) by the system.  When used with a PRIMARY KEY or UNIQUE constraint, the constraint-name may be used as the name of an index that is created to support the constraint.  PRIMARY KEY  This provides a shorthand method of defining a primary key composed of a single column. Thus, if PRIMARY KEY is specified in the definition of column C, the effect is the same as if the PRIMARY KEY(C) clause is specified as a separate clause.  A primary key cannot be specified if the table is a subtable (SQLSTATE 429B3) since the primary key is inherited from the supertable.  See PRIMARY KEY within the description of the unique-constraint below.  UNIQUE  This provides a shorthand method of defining a unique key composed of a single column. Thus, if UNIQUE is specified in the definition of column C, the effect is the same as if the UNIQUE(C) clause is specified as a separate clause.  A unique constraint cannot be specified if the table is a subtable (SQLSTATE 429B3) since unique constraints are inherited from the supertable.  See UNIQUE within the description of the unique-constraint below.  references-clause  This provides a shorthand method of defining a foreign key composed of a single column. Thus, if a references-clause is specified in the definition of column C, the effect is the same as if that references-clause were specified as part of a FOREIGN KEY clause in which C is the only identified column.  See references-clause under referential-constraint below.  CHECK (check-condition)  This provides a shorthand method of defining a check constraint that applies to a single column. See CHECK (check-condition) below.  unique-constraint  Defines a unique or primary key constraint. If the table has a partitioning key, then any unique or primary key must be a superset of the partitioning key. A unique or primary key constraint cannot be specified for a table that is a subtable (SQLSTATE 429B3). If the table is a root table, the constraint applies to the table and all its subtables.  CONSTRAINT constraint-name  Names the primary key or unique constraint. See page ***.  UNIQUE (column-name,...)  Defines a unique key composed of the identified columns. The identified columns must be defined as NOT NULL. Each column-name must identify a column of the table and the same column must not be identified more than once. The number of identified columns must not exceed 16 and the sum of their length attributes must not exceed 255. No LOB, LONG VARCHAR, LONG VARGRAPHIC, or DATALINK column may be used as part of a unique key (even if the length attribute of the column is small enough to fit within the 255 byte limit) (SQLSTATE 42962). The set of columns in the unique key cannot be the same as the set of columns of the primary key or another unique key (SQLSTATE 01543). (64)  A unique constraint cannot be specified if the table is a subtable (SQLSTATE 429B3) since unique constraints are inherited from the supertable.  The description of the table as recorded in the catalog includes the unique key and its unique index. A unique index will automatically be created for the columns in the sequence specified with ascending order for each column. The name of the index will be the same as the constraint-name if this does not conflict with an existing index in the schema where the table is created. If the index name conflicts, the name will be SQL, followed by a character timestamp (yymmddhhmmssxxx), with SYSIBM as the schema name.  PRIMARY KEY (column-name,...)  Defines a primary key composed of the identified columns. The clause must not be specified more than once and the identified columns must be defined as NOT NULL. Each column-name must identify a column of the table and the same column must not be identified more than once. The number of identified columns must not exceed 16 and the sum of their length attributes must not exceed 255. No LOB, LONG VARCHAR, LONG VARGRAPHIC, or DATALINK column may be used as part of a primary key (even if the length attribute of the column is small enough to fit within the 255 byte limit) (SQLSTATE 42962). The set of columns in the primary key cannot be the same as the set of columns of a unique key (SQLSTATE 01543). (64)  Only one primary key can be defined on a table.  A primary key cannot be specified if the table is a subtable (SQLSTATE 429B3) since the primary key is inherited from the supertable.  The description of the table as recorded in the catalog includes the primary key and its primary index. A unique index will automatically be created for the columns in the sequence specified with ascending order for each column. The name of the index will be the same as the constraint-name if this does not conflict with an existing index in the schema where the table is created. If the index name conflicts, the name will be SQL, followed by a character timestamp (yymmddhhmmssxxx), with SYSIBM as the schema name.  If the table has a partitioning key, the columns of a unique-constraint must be a superset of the partitioning key columns; column order is unimportant.  referential-constraint  Defines a referential constraint. A referential constraint cannot be defined from a typed table or to a parent table that is a typed table (SQLSTATE 42997).  CONSTRAINT constraint-name  Names the referential constraint. See page ***.  FOREIGN KEY (column-name,...)  Defines a referential constraint with the specified constraint-name.  Let T1 denote the object table of the statement. The foreign key of the referential constraint is composed of the identified columns. Each name in the list of column names must identify a column of T1 and the same column must not be identified more than once. The number of identified columns must not exceed 16 and the sum of their length attributes must not exceed 255 minus the number of columns that allow null values. No LOB, LONG VARCHAR, LONG VARGRAPHIC or DATALINK column may be used as part of a foreign key (SQLSTATE 42962). There must be the same number of foreign key columns as there are in the parent key and the data types of the corresponding columns must be compatible (SQLSTATE 42830). Two column descriptions are compatible if they have compatible data types (both columns are numeric, character strings, graphic, date/time, or have the same distinct type).  references-clause  Specifies the parent table and parent key for the referential constraint.  REFERENCES table-name  The table specified in a REFERENCES clause must identify a base table that is described in the catalog, but must not identify a catalog table.  A referential constraint is a duplicate if its foreign key, parent key, and parent table are the same as the foreign key, parent key and parent table of a previously specified referential constraint. Duplicate referential constraints are ignored and a warning is issued (SQLSTATE 01543).  In the following discussion, let T2 denote the identified parent table and let T1 denote the table being created (65) (T1 and T2 may be the same table).  The specified foreign key must have the same number of columns as the parent key of T2 and the description of the nth column of the foreign key must be comparable to the description of the nth column of that parent key. Datetime columns are not considered to be comparable to string columns for the purposes of this rule.  (column-name,...)  The parent key of a referential constraint is composed of the identified columns. Each column-name must be an unqualified name that identifies a column of T2. The same column must not be identified more than once.  The list of column names must match the set of columns (in any order) of the primary key or a unique constraint that exists on T2 (SQLSTATE 42890). If a column name list is not specified, then T2 must have a primary key (SQLSTATE 42888). Omission of the column name list is an implicit specification of the columns of that primary key in the sequence originally specified.  The referential constraint specified by a FOREIGN KEY clause defines a relationship in which T2 is the parent and T1 is the dependent.  rule-clause  Specifies what action to take on dependent tables.  ON DELETE  Specifies what action is to take place on the dependent tables when a row of the parent table is deleted. There are four possible actions:  NO ACTION (default)  RESTRICT  CASCADE  SET NULL  The delete rule applies when a row of T2 is the object of a DELETE or propagated delete operation and that row has dependents in T1. Let p denote such a row of T2.  If RESTRICT or NO ACTION is specified, an error occurs and no rows are deleted.  If CASCADE is specified, the delete operation is propagated to the dependents of p in T1.  If SET NULL is specified, each nullable column of the foreign key of each dependent of p in T1 is set to null.  SET NULL must not be specified unless some column of the foreign key allows null values. Omission of the clause is an implicit specification of ON DELETE NO ACTION.  A cycle involving two or more tables must not cause a table to be delete-connected to itself unless all of the delete rules in the cycle are CASCADE. Thus, if the new relationship would form a cycle and T2 is already delete connected to T1, then the constraint can only be defined if it has a delete rule of CASCADE and all other delete rules of the cycle are CASCADE.  If T1 is delete-connected to T2 through multiple paths, those relationships in which T1 is a dependent and which form all or part of those paths must have the same delete rule and it must not be SET NULL. The NO ACTION and RESTRICT actions are treated identically. Thus, if T1 is a dependent of T3 in a relationship with a delete rule of r, the referential constraint cannot be defined when r is SET NULL if any of these conditions exist:  T2 and T3 are the same table  T2 is a descendant of T3 and the deletion of rows from T3 cascades to T2  T3 is a descendant of T2 and the deletion of rows from T2 cascades to T3  T2 and T3 are both descendants of the same table and the deletion of rows from that table cascades to both T2 and T3.  If r is other than SET NULL, the referential constraint can be defined, but the delete rule that is implicitly or explicitly specified in the FOREIGN KEY clause must be the same as r.  ON UPDATE  Specifies what action is to take place on the dependent tables when a row of the parent table is updated. The clause is optional. ON UPDATE NO ACTION is the default and ON UPDATE RESTRICT is the only alternative.  The difference between NO ACTION and RESTRICT is described under CREATE TABLE in Notes.  check-constraint  Defines a check constraint. A check-constraint is a search-condition that must evaluate to not false. A check constraint cannot be defined on a typed table (SQLSTATE 42997).  CONSTRAINT constraint-name  Names the check constraint. See page ***.  CHECK (check-condition)  Defines a check constraint. A check-condition is a search-condition except as follows:  A column reference must be to a column of the table being created  It cannot contain any of the following:  subqueries  dereference operations or DEREF functions where the reference value is other than the object identifier column  column functions  variant user-defined functions  user-defined functions using the EXTERNAL ACTION option  user-defined functions using the SCRATCHPAD option  host variables  parameter markers  special registers  an alias  If a check constraint is specified as part of a column-definition then a column reference can only be made to the same column. Check constraints specified as part of a table definition can have column references identifying columns previously defined in the CREATE TABLE statement.  Check constraints are not checked for inconsistencies, duplicate conditions or equivalent conditions. Therefore, contradictory or redundant check constraints can be defined resulting in possible errors at execution time.  The check-condition "IS NOT NULL" can be specified, however it is recommended that nullability be enforced directly using the NOT NULL attribute of a column. For example, CHECK (salary + bonus > 30000) is accepted if salary is set to NULL, because CHECK constraints must be either satisfied or unknown and in this case salary is unknown. However, CHECK (salary IS NOT NULL) would be considered false and a violation of the constraint if salary is set to NULL.  Check constraints are enforced when rows in the table are inserted or updated. A check constraint defined on a table automatically applies to all subtables of that table.  OID-column-definition  Defines the object identifier column for the typed table.  REF IS OID-column-name USER GENERATED  Specifies that an object identifier (OID) column is defined in the table as the first column. An OID is required for the root table of a table hierarchy (SQLSTATE 428DX). The table must be a typed table (the OF clause must be present) that is not a subtable (SQLSTATE 42613). The name for the column is defined as OID-column-name and cannot be the same as the name of any attribute of the structured type type-name1 (SQLSTATE 42711). The column is defined with type REF(type-name1), NOT NULL and a system required unique index (with a default index name) is generated. This column is referred to as the object identifier column or OID column. The keywords USER GENERATED indicate that the initial value for the OID column must be provided by the user when inserting a row. Once a row is inserted, the OID column cannot be updated (SQLSTATE 42808).  with-options  Defines additional options that apply to columns of a typed table.  column-name  Specifies the name of the column for which additional options are specified. The column-name must correspond to the name of a column of the table that is not also a column of a supertable (SQLSTATE 428DJ). A column name can only appear in one WITH OPTIONS clause in the statement (SQLSTATE 42613).  If an option is already specified as part of the type definition (in CREATE TYPE), the options specified here override the options in CREATE TYPE.  WITH OPTIONS column-options  Defines options for the specified column. See column-options described earlier. If the table is a subtable, primary key or unique constraints cannot be specified (SQLSTATE 429B3).  DATA CAPTURE  Indicates whether extra information for inter-database data replication is to be written to the log. This clause cannot be specified when creating a subtable (SQLSTATE 42613).  NONE  Indicates that no extra information will be logged.  CHANGES  Indicates that extra information regarding SQL changes to this table will be written to the log. This option is required if this table will be replicated and the Capture program is used to capture changes for this table from the log.  If the table is defined to allow data on a partition other than the catalog partition (multiple partition nodegroup or nodegroup with a partition other than the catalog partition), then this option is not supported (SQLSTATE 42997).  Further information about using replication can be found in the Administration Guide and the DB2 Replication Guide and Reference.  IN tablespace-name1  Identifies the table space in which the table will be created. The table space must exist, and be a REGULAR table space. If no other table space is specified, then all table parts will be stored in this table space. This clause cannot be specified when creating a subtable (SQLSTATE 42613), since the table space is inherited from the root table of the table hierarchy. If this clause is not specified, a table space for the table is determined as follows:  IF table space IBMDEFAULTGROUP exists with sufficient page size    THEN use it ELSE IF user created table space exists with sufficient page size     THEN use it ELSE IF table space USERSPACE1 exists with sufficient page size     THEN use it ELSE IF USERSPACE8K exists with sufficient page size     THEN use it ELSE issue an error (SQLSTATE 42727). The sufficient page size of a table is determined by either the byte count of the row or the number of columns. Refer to Row Size for more information. If the table includes one or more LOB columns, then only a 4K page size table space can be used. If the number of columns or the row size would require an 8K page size table space, then a default cannot be select and an error is returned (SQLSTATE 42997). In this situation an 8K page size DMS table space should be specified with a 4K page size DMS table space in the LONG IN clause.  tablespace-options:  Specifies the table space in which indexes and/or long column values will be stored. See CREATE TABLESPACE for details on types of table spaces.  INDEX IN tablespace-name2  Identifies the table space in which any indexes on the table will be created. This option is allowed only when the primary table space specified in the IN clause is a DMS table space. The specified table space must exist, be a REGULAR DMS table space and must be in the same nodegroup as tablespace-name1 (SQLSTATE 42838).  Note that specifying which table space will contain a table's index can only be done when the table is created.  LONG IN tablespace-name3  Identifies the table space in which the values of any long columns (LONG VARCHAR, LONG VARGRAPHIC, LOB data types, or distinct types with any of these as source types) will be stored. This option is allowed only when the primary table space specified in the IN clause is a DMS table space. The table space must exist, be a LONG DMS table space and must be in the same nodegroup of tablspace-name1 (SQLSTATE 42838).  PARTITIONING KEY (column-name,...)  Specifies the partitioning key used when data in the table is partitioned. Each column-name must identify a column of the table and the same column must not be identified more than once. No LOB, LONG VARCHAR, LONG VARGRAPHIC or DATALINK column may be used as part of a partitioning key (SQLSTATE 42962). A partitioning key cannot be specified for a table that is a subtable (SQLSTATE 42613), since the partitioning key is inherited from the root table in the table hierarchy.  If this clause is not specified, and this table resides in a multiple partition nodegroup, then the partitioning key is defined as follows:  if the table is a typed table, the object identifier column  if a primary key is specified, the first column of the primary key is the partitioning key  otherwise, the first non-long column (LOB or long column type) is the partitioning key.  If none of the columns satisfy the requirement of the default partitioning key, the table is created without one. Such tables are allowed only in table spaces defined on single-partition nodegroups.  For tables in table spaces defined on single-partition nodegroups, any collection of non-long type columns can be used to define the partitioning key. If you do not specify this parameter, no partitioning key is created.  For restrictions related to the partitioning key, see Rules.  USING HASHING  Specifies the use of the hashing function as the partitioning method for data distribution. This is the only partitioning method supported.  REPLICATED  Specifies that the data stored in the table is physically replicated on each database partition of the nodegroup of the table space in which the table is defined. This means that a copy of all the data in the table exists on each of these database partitions. This option can only be specified for a summary table defined with REFRESH IMMEDIATE (SQLSTATE 42997). A unique index must exist on the underlying table where the index key columns are included in the select list of the fullselect that defines the summary table.  NOT LOGGED INITIALLY  Any changes made to the table by an Insert, Delete, Update, Create Index, Drop Index, or Alter Table operation in the same unit of work in which the table is created are not logged. See Notes for other considerations when using this option.  All catalog changes and storage related information are logged, as are all operations that are done on the table in subsequent units of work.  A foreign key constraint cannot be defined on a table that references a parent with the NOT LOGGED INITIALLY attribute. This clause cannot be specified when creating a subtable (SQLSTATE 42613). Note: An error in any operation in the unit of work in which the table is created will result in the entire unit of work being rolled back.   Rules  The sum of the byte counts of the columns must not be greater than the row size limit that is based on the page size of the table space (SQLSTATE 54010). Refer to Byte Counts and Table 27 for more information. For typed tables, the byte count is applied to the columns of the root table of the table hierarchy and every additional column introduced by every subtable in the table hierarchy (additional subtable columns must be considered nullable for byte count purposes, even when defined as not nullable). There is also an additional 4 bytes of overhead to identify the subtable to which each row belongs.  The number of columns in a table cannot exceed 1012 (SQLSTATE 54011). For typed tables, the total number of attributes of the types of all of the subtables in the table hierarchy cannot exceed 1010.  An object identifier column of a typed table cannot be updated (SQLSTATE 42808).  A partitioning key column of a table cannot be updated (SQLSTATE 42997).  Any unique or primary key constraint defined on the table must be a superset of the partitioning key (SQLSTATE 42997).  A nullable column of a partitioning key cannot be included as a foreign key column when the relationship is defined with ON DELETE SET NULL (SQLSTATE 42997).  The following table provides the supported combinations of DATALINK options in the file-link-options (SQLSTATE 42613).  Table 18. Valid DATALINK File Control Option Combinations INTEGRITY  READ PERMISSION  WRITE PERMISSION  RECOVERY  ON UNLINK   ALL  FS  FS  NO  Not applicable   ALL  FS  BLOCKED  NO  RESTORE   ALL  FS  BLOCKED  YES  RESTORE   ALL  DB  BLOCKED  NO  RESTORE   ALL  DB  BLOCKED  NO  DELETE   ALL  DB  BLOCKED  YES  RESTORE   ALL  DB  BLOCKED  YES  DELETE   The following rules only apply to partitioned databases.  Tables composed of only long columns can only be created in table spaces defined on single-partition nodegroups.  The partitioning key definition of a table in a table space defined on a multiple partition nodegroup cannot be altered.  The partitioning key column of a typed table must be the OID column.  Notes  Creating a table with a schema name that does not already exist will result in the implicit creation of that schema provided the authorization ID of the statement has IMPLICIT_SCHEMA authority. The schema owner is SYSIBM. The CREATEIN privilege on the schema is granted to PUBLIC.  If a foreign key is specified:  All packages with a delete usage on the parent table are invalidated.  All packages with an update usage on at least one column in the parent key are invalidated.  Creating a subtable causes invalidation of all packages that depend on any table in table hierarchy.  The use of NO ACTION or RESTRICT as delete or update rules for referential constraints determines when the constraint is enforced. A delete or update rule of RESTRICT is enforced before all other constraints including those referential constraints with modifying rules such as CASCADE or SET NULL. A delete or update rule of NO ACTION is enforced after other referential constraints. There are very few cases where this can make a difference during a delete or update. One example where different behavior is evident involves a DELETE of rows in a view that is defined as a UNION ALL of related tables.    Table T1 is a parent of table T3, delete rule as noted below   Table T2 is a parent of table T3, delete rule CASCADE     CREATE VIEW V1 AS SELECT * FROM T1 UNION ALL SELECT * FROM T2     DELETE FROM V1 If table T1 is a parent of table T3 with delete rule of RESTRICT, a restrict violation will be raised (SQLSTATE 23001) if there are any child rows for parent keys of T1 in T3.  If table T1 is a parent of table T3 with delete rule of NO ACTION, the child rows may be deleted by the delete rule of CASCADE when deleting rows from T2 before the NO ACTION delete rule is enforced for the deletes from T1. If deletes from T2 did not result in deleting all child rows for parent keys of T1 in T3, then a constraint violation will be raised (SQLSTATE 23504).  Note that the SQLSTATE returned is different depending on whether the delete or update rule is RESTRICT or NO ACTION.  For tables in table spaces defined on multiple partition nodegroups, table collocation should be considered in choosing the partitioning keys. Following is a list of items to consider:  The tables must be in the same nodegroup for collocation. The table spaces may be different, but must be defined in the same nodegroup.  The partitioning keys of the tables must have the same number of columns, and the corresponding key columns must be partition compatible for collocation. For more information, see Partition Compatibility.  The choice of partitioning key also has an impact on performance of joins. If a table is frequently joined with another table, you should consider the joining column(s) as a partitioning key for both tables.  The NOT LOGGED INITIALLY option is useful for situations where a large result set needs to be created with data from an alternate source (another table or a file) and recovery of the table is not necessary. Using this option will save the overhead of logging the data. The following considerations apply when this option is specified:  When the unit of work is committed, all changes that were made to the table during the unit of work are flushed to disk.  When you run the Rollforward utility and it encounters a log record that indicates that a table in the database was either populated by the Load utility or created with the NOT LOGGED INITIALLY option, the table will be marked as unavailable. The table will be dropped by the Rollforward utility if it later encounters a DROP TABLE log. Otherwise, after the database is recovered, an error will be issued if any attempt is made to access the table (SQLSTATE 55019). The only operation permitted is to drop the table.  Once such a table is backed up as part of a database or table space back up, recovery of the table becomes possible.  A REFRESH DEFERRED summary table may be used to optimize the processing queries. In order for this optimization be able to use a summary table, the fullselect must conform to certain rules in addition to those already described. The fullselect must:  be a subselect with a GROUP BY clause  not include DISTINCT anywhere in the select list  not include any grouping sets (including CUBE or ROLLUP)  not include any special registers  not include functions that are not deterministic.  does not conform to these rules, a warning is returned (SQLSTATE 01633).  Inoperative summary tables:  An inoperative summary table is a table that is no longer available for SQL statements. A summary table becomes inoperative if:  A privilege upon which the summary table definition is dependent is revoked.  An object such as a table, alias or function, upon which the summary table definition is dependent is dropped.  In practical terms, an inoperative summary table is one in which the summary table definition has been unintentionally dropped. For example, when an alias is dropped, any summary table defined using that alias is made inoperative. All packages dependent on the summary table are no longer valid.  Until the inoperative summary table is explicitly recreated or dropped, a statement using that inoperative summary table cannot be compiled (SQLSTATE 51024) with the exception of the CREATE ALIAS, CREATE TABLE, DROP TABLE, and COMMENT ON TABLE statements. Until the inoperative summary table has been explicitly dropped, its qualified name cannot be used to create another view, base table or alias. (SQLSTATE 42710).  An inoperative summary table may be recreated by issuing a CREATE TABLE statement using the definition text of the inoperative summary table. This summary table query text is stored in the TEXT column of the SYSCAT.VIEWS catalog. When recreating an inoperative summary table, it is necessary to explicitly grant any privileges required on that table by others, due to the fact that all authorization records on a summary table are deleted if the summary table is marked inoperative. Note that there is no need to explicitly drop the inoperative summary table in order to recreate it. Issuing a CREATE TABLE statement that defines a summary table with the same table-name as an inoperative summary table will cause that inoperative summary table to be replaced, and the CREATE TABLE statement will return a warning (SQLSTATE 01595).  Inoperative summary tables are indicated by an X in the VALID column of the SYSCAT.VIEWS catalog view and an X in the STATUS column of the SYSCAT.TABLES catalog view.  Privileges:  When any table is created, the definer of the table is granted CONTROL privilege. When a subtable is created, the SELECT privilege that each user or group has on the the immediate supertable is automatically granted on the subtable with the table definer as the grantor.  Row Size:  The maximum number of bytes allowed in the row of a table is dependent on the page size of the the table space in which the table is created (tablspace-name1). The following list shows the row size limit and number of columns limit associated with each table space page size.  Table 19. Limits for Number of Columns and Row Size in Each Table Space Page Size Page Size  Row Size Limit  Column Count Limit   4K  4005  500   8K  8101  1012   Byte Counts:  The following list contains the byte counts of columns by data type for columns that do not allow null values. For a column that allows null values the byte count is one more than shown in the list.  If the table is created based on a structured type, an additional 4 bytes of overhead is reserved to identify rows of subtables regardless of whether or not subtables are defined. Also, additional subtable columns must be considered nullable for byte count purposes, even when defined as not nullable.  Data type  Byte count  INTEGER  4  SMALLINT  2  BIGINT  8  REAL  4  DOUBLE  8  DECIMAL  The integral part of (p/2)+1, where p is the precision.  CHAR(n)  n  VARCHAR(n)  n+4  LONG VARCHAR  24  GRAPHIC(n)  n*2  VARGRAPHIC(n)  (n*2)+4  LONG VARGRAPHIC  24  DATE  4  TIME  3  TIMESTAMP  10  DATALINK(n)  n+54  LOB types  Each LOB value has a LOB descriptor in the base record that points to the location of the actual value. The size of the descriptor varies according to the maximum length defined for the column. The following table shows typical sizes:    Maximum LOB Length    LOB Descriptor Size                1 024                     72                8 192                     96               65 536                    120              524 000                    144            4 190 000                    168          134 000 000                    200          536 000 000                    224        1 070 000 000                    256        1 470 000 000                    280        2 147 483 647                    316 Distinct type  Length of the source type of the distinct type.  Reference type  Length of the built-in data type on which the reference type is based.  Examples  Example 1:  Create table TDEPT in the DEPARTX table space. DEPTNO, DEPTNAME, MGRNO, and ADMRDEPT are column names. CHAR means the column will contain character data. NOT NULL means that the column cannot contain a null value. VARCHAR means the column will contain varying-length character data. The primary key consists of the column DEPTNO.     CREATE TABLE TDEPT      (DEPTNO   CHAR(3)     NOT NULL,       DEPTNAME VARCHAR(36) NOT NULL,       MGRNO    CHAR(6),       ADMRDEPT CHAR(3)     NOT NULL,       PRIMARY KEY(DEPTNO))    IN DEPARTX Example 2:  Create table PROJ in the SCHED table space. PROJNO, PROJNAME, DEPTNO, RESPEMP, PRSTAFF, PRSTDATE, PRENDATE, and MAJPROJ are column names. CHAR means the column will contain character data. DECIMAL means the column will contain packed decimal data. 5,2 means the following: 5 indicates the number of decimal digits, and 2 indicates the number of digits to the right of the decimal point. NOT NULL means that the column cannot contain a null value. VARCHAR means the column will contain varying-length character data. DATE means the column will contain date information in a three-part format (year, month, and day).     CREATE TABLE PROJ      (PROJNO   CHAR(6)      NOT NULL,       PROJNAME VARCHAR(24)  NOT NULL,       DEPTNO   CHAR(3)      NOT NULL,       RESPEMP  CHAR(6)      NOT NULL,       PRSTAFF  DECIMAL(5,2)         ,       PRSTDATE DATE                 ,       PRENDATE DATE                 ,       MAJPROJ  CHAR(6)      NOT NULL)    IN SCHED Example 3:  Create a table called EMPLOYEE_SALARY where any unknown salary is considered 0. No table space is specified, so that the table will be created in a table space selected by the system based on the rules descirbed for the IN tablespace-name1 clause.     CREATE TABLE EMPLOYEE_SALARY      (DEPTNO   CHAR(3)      NOT NULL,       DEPTNAME VARCHAR(36)  NOT NULL,       EMPNO    CHAR(6)      NOT NULL,       SALARY   DECIMAL(9,2) NOT NULL WITH DEFAULT) Example 4:  Create distinct types for total salary and miles and use them for columns of a table created in the default table space. In a dynamic SQL statement assume the CURRENT SCHEMA special register is JOHNDOE and the CURRENT PATH is the default ("SYSIBM","SYSFUN","JOHNDOE").  If a value for SALARY is not specified it must be set to 0 and if a value for LIVING_DIST is not specified it must to set to 1 mile.    CREATE DISTINCT TYPE JOHNDOE.T_SALARY AS INTEGER WITH COMPARISONS     CREATE DISTINCT TYPE JOHNDOE.MILES AS FLOAT WITH COMPARISONS     CREATE TABLE EMPLOYEE      (ID          INTEGER NOT NULL,       NAME        CHAR (30),       SALARY      T_SALARY NOT NULL WITH DEFAULT,       LIVING_DIST MILES    DEFAULT MILES(1) ) Example 5:  Create distinct types for image and audio and use them for columns of a table. No table space is specified, so that the table will be created in a table space selected by the system based on the rules descirbed for the IN tablespace-name1 clause. Assume the CURRENT PATH is the default.    CREATE DISTINCT TYPE IMAGE AS BLOB (10M)     CREATE DISTINCT TYPE AUDIO AS BLOB (1G)     CREATE TABLE PERSON      (SSN    INTEGER NOT NULL,       NAME   CHAR (30),       VOICE  AUDIO,       PHOTO  IMAGE) Example 6:  Create table EMPLOYEE in the HUMRES table space. The constraints defined on the table are the following:  The values of department number must lie in the range 10 to 100.  The job of an employee can only be either 'Sales', 'Mgr' or 'Clerk'.  Every employee that has been with the company since 1986 must make more than $40,500.  Note: If the columns included in the check constraints are nullable they could also be NULL.     CREATE TABLE EMPLOYEE    (ID          SMALLINT NOT NULL,     NAME        VARCHAR(9),     DEPT        SMALLINT CHECK (DEPT BETWEEN 10 AND 100),     JOB         CHAR(5) CHECK (JOB IN ('Sales','Mgr','Clerk')),     HIREDATE    DATE,     SALARY      DECIMAL(7,2),     COMM        DECIMAL(7,2),     PRIMARY KEY (ID),     CONSTRAINT  YEARSAL CHECK (YEAR(HIREDATE) > 1986 OR SALARY > 40500)    )    IN HUMRES   Example 7:  Create a table that is wholly contained in the PAYROLL table space.     CREATE TABLE EMPLOYEE .....       IN PAYROLL Example 8:  Create a table with its data part in ACCOUNTING and its index part in ACCOUNT_IDX.     CREATE TABLE SALARY.....       IN ACCOUNTING INDEX IN ACCOUNT_IDX Example 9:  Create a table and log SQL changes in the default format.     CREATE TABLE SALARY1 ..... or     CREATE TABLE SALARY1 .....       DATA CAPTURE NONE Example 10:  Create a table and log SQL changes in an expanded format.     CREATE TABLE SALARY2 .....       DATA CAPTURE CHANGES Example 11:  Create a table EMP_ACT in the SCHED table space. EMPNO, PROJNO, ACTNO, EMPTIME, EMSTDATE, and EMENDATE are column names. Constraints defined on the table are:  The value for the set of columns, EMPNO, PROJNO, and ACTNO, in any row must be unique.  The value of PROJNO must match an existing value for the PROJNO column in the PROJECT table and if the project is deleted all rows referring to the project in EMP_ACT should also be deleted.     CREATE TABLE EMP_ACT    (EMPNO       CHAR(6) NOT NULL,     PROJNO      CHAR(6) NOT NULL,     ACTNO       SMALLINT NOT NULL,     EMPTIME     DECIMAL(5,2),     EMSTDATE    DATE,     EMENDATE    DATE,     CONSTRAINT EMP_ACT_UNIQ UNIQUE (EMPNO,PROJNO,ACTNO),     CONSTRAINT FK_ACT_PROJ FOREIGN KEY (PROJNO)                            REFERENCES PROJECT (PROJNO) ON DELETE CASCADE    )    IN SCHED A unique index called EMP_ACT_UNIQ is automatically created in the same schema to enforce the unique constraint.  Example 12:  Create a table that is to hold information about famous goals for the ice hockey hall of fame. The table will list information about the player who scored the goal, the goaltender against who it was scored, the date and place, and a description. When available, it will also point to places where newspaper articles about the game are stored and where still and moving pictures of the goal are stored. The newspaper articles are to be linked so they cannot be deleted or renamed but all existing display and update applications must continue to operate. The still pictures and movies are to be linked with access under complete control of DB2. The still pictures are to have recovery and are to be returned to their original owner if unlinked. The movie pictures are not to have recovery and are to be deleted if unlinked. The description column and the three DATALINK columns are nullable.    CREATE TABLE HOCKEY_GOALS     ( BY_PLAYER        VARCHAR(30)   NOT NULL,       BY_TEAM          VARCHAR(30)   NOT NULL,       AGAINST_PLAYER   VARCHAR(30)   NOT NULL,       AGAINST_TEAM     VARCHAR(30)   NOT NULL,       DATE_OF_GOAL     DATE          NOT NULL,       DESCRIPTION      CLOB(5000),       ARTICLES         DATALINK  LINKTYPE URL FILE LINK CONTROL MODE DB2OPTIONS,       SNAPSHOT         DATALINK  LINKTYPE URL FILE LINK CONTROL                                  INTEGRITY ALL                                  READ PERMISSION DB WRITE PERMISSION BLOCKED                                  RECOVERY YES ON UNLINK RESTORE,       MOVIE            DATALINK  LINKTYPE URL FILE LINK CONTROL                                  INTEGRITY ALL                                  READ PERMISSION DB WRITE PERMISSION BLOCKED                                  RECOVERY NO ON UNLINK DELETE ) -------------------------------------------------------------------------------- Footnotes:  (61) Observe that it is not possible to specify the FOR BIT DATA clause for CLOB columns. However, a CHAR FOR BIT DATA string can be assigned to a CLOB column and a CHAR FOR BIT DATA string can be concatenated with a CLOB string.  (62) With DB2 Universal Database, the file is assigned to a special predefined "dfmunknown" user id.  (63) The identifier is formed of "SQL" followed by a sequence of 15 numeric characters generated by a timestamp-based function.  (64) If LANGLEVEL is SQL92E or MIA then an error is returned, SQLSTATE 42891.  (65) or altered, in the case where this clause is referenced from the description of the ALTER TABLE statement. 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值