|
The SQL ALTER TABLE statement is used to add, delete, or modify columns in an existing table.
The ALTER TABLE statement is also used to add and drop various constraints on an existing table.
Following is the table alteration syntax:
A instrução SQL ALTER TABLE é usada para adicionar, excluir ou modificar colunas em uma tabela existente.
A instrução ALTER TABLE também é usada para adicionar e eliminar várias restrições em uma tabela existente.
A seguir está a sintaxe de alteração da tabela:
ALTER TABLE table-name
[ADD column-definition
table-constraint-clause]
[ALTER COLUMN column-alteration]
[DROP CONSTRAINT constraint-name|
PRIMARY KEY|
UNIQUE (column-name [,column-name...])]
[RENAME COLUMN source-column-name
TO target-column-name]
column-alteration
[SET DATA TYPE (altered-data-type)]
[SET default-clause]
[DROP DEFAULT]
|
Column DEPT_NAME in table DSN8910.TB_DEPARTMENT was created as a VARCHAR(36).
Increase its length to 60 bytes. Also, add the column DEPT_BLDG to the table DSN8910.TB_DEPARTMENT.
Describe the new column as a character string column of length is 5.
A coluna DEPT_NAME na tabela DSN8910.TB_DEPARTMENT foi criada como um VARCHAR (36).
Aumente seu comprimento para 60 bytes. Além disso, adicione a coluna DEPT_BLDG à tabela DSN8910.TB_DEPARTMENT.
Descreva a nova coluna como uma coluna de sequência de caracteres de comprimento 5.
ALTER TABLE DSN8910.TB_DEPARTMENT
ALTER COLUMN DEPT_NAME
SET DATA TYPE VARCHAR(60)
ADD DEPT_BLDG CHAR(5);
|
Alter the TB_PRODINFO table to define a foreign key that references a non-primary unique key in the product version table (TB_PRODVER).
The columns of the unique key are PRODVER_NAME and PRODVER_RELNO.
Altere a tabela TB_PRODINFO para definir uma chave estrangeira que faz referência a uma chave exclusiva não primária na tabela de versão do produto (TB_PRODVER).
As colunas da chave única são PRODVER_NAME e PRODVER_RELNO.
ALTER TABLE TB_PRODINFO
FOREIGN KEY (PRODINFO_NAME, PRODINFO_VERNO)
REFERENCES TB_PRODVER (PRODVER_NAME, PRODVER_RELNO)
ON DELETE RESTRICT;
|
Adicione uma coluna chamada RATING, que tem um caracter, à tabela DEPARTMENT.
Add a column named RATING, which is one character long, to the DEPARTMENT table.
ALTER TABLE DEPARTMENT
ADD RATING CHAR(1)
|
Adicione uma coluna chamada SITE_NOTES à tabela PROJECT. Crie SITE_NOTES como uma coluna de comprimento variável com um comprimento máximo de 1000
bytes.
Os valores da coluna não possuem um conjunto de caracteres associado e, portanto, não devem ser convertidos.
Add a column named SITE_NOTES to the PROJECT table. Create SITE_NOTES as a varying-length column with a maximum length of 1000 bytes.
The values of the column do not have an associated character set and therefore must not be converted.
ALTER TABLE PROJECT
ADD SITE_NOTES VARCHAR(1000) FOR BIT DATA
|
Suponha que exista uma tabela chamada EQUIPAMENT definida com as seguintes colunas:
Assume a table that is called EQUIPMENT exists defined with the following columns:
Column Name Data Type
EQUIP_NO INT
EQUIP_DESC VARCHAR(50)
LOCATION VARCHAR(50)
EQUIP_OWNER CHAR(3)
|
Adicione uma restrição referencial à tabela EQUIPMENT para que o proprietário (EQUIP_OWNER) seja um número de departamento (DEPTNO) presente na tabela
DEPARTMENT. DEPTNO é a chave primária da tabela DEPARTMENT.
Se um departamento for removido da tabela DEPARTMENT, os valores do proprietário (EQUIP_OWNER) para todos os equipamentos pertencentes a esse
departamento devem se tornar não atribuídos (ou definidos como nulos). Dê à restrição o nome DEPTQUIP.
Add a referential constraint to the EQUIPMENT table so that the owner (EQUIP_OWNER) must be a department number (DEPTNO) that is present in the
DEPARTMENT table. DEPTNO is the primary key of the DEPARTMENT table.
If a department is removed from the DEPARTMENT table, the owner (EQUIP_OWNER) values for all equipment that is owned by that department should become
unassigned (or set to null). Give the constraint the name DEPTQUIP.
ALTER TABLE EQUIPMENT
ADD CONSTRAINT DEPTQUIP
FOREIGN KEY (EQUIP_OWNER)
REFERENCES DEPARTMENT
ON DELETE SET NULL
|
Além disso, uma coluna extra é necessária para permitir o registro da quantidade que está associada a este registro do equipamento.
A menos que especificado de outra forma, a coluna EQUIP_QTY deve ter um valor de 1 e nunca deve ser nula.
Also, an extra column is needed to allow the recording of the quantity that is associated with this equipment record.
Unless otherwise specified, the EQUIP_QTY column should have a value of 1 and must never be null.
ALTER TABLE EQUIPMENT
ADD COLUMN EQUIP_QTY
SMALLINT NOT NULL DEFAULT 1
|
Alterar tabela EMPLOYEE.
Adicione a restrição de verificação chamada REVENUE definida para que cada funcionário receba um total de salário e comissão superior a $ 30.000.
Alter table EMPLOYEE.
Add the check constraint that is named REVENUE defined so that each employee must make a total of salary and commission greater
than $30,000.
ALTER TABLE EMPLOYEE
ADD CONSTRAINT REVENUE
CHECK (SALARY + COMM > 30000)
|
Alterar tabela EMPLOYEE.
Elimine a restrição REVENUE, que foi definida anteriormente.
Alter table EMPLOYEE.
Drop the constraint REVENUE, which was previously defined.
ALTER TABLE EMPLOYEE
DROP CONSTRAINT REVENUE
|
Altere uma tabela para registrar as alterações de SQL no formato padrão.
Alter a table to log SQL changes in the default format.
ALTER TABLE SALARY1
DATA CAPTURE NONE
|
Altere uma tabela para registrar as alterações de SQL em um formato expandido.
Alter a table to log SQL changes in an expanded format.
ALTER TABLE SALARY2
DATA CAPTURE CHANGES
|
Altere a tabela EMPLOYEE para adicionar quatro novas colunas com valores padrão.
Alter the EMPLOYEE table to add four new columns with default values.
ALTER TABLE EMPLOYEE
ADD COLUMN HEIGHT MEASURE DEFAULT MEASURE(1)
ADD COLUMN BIRTHDAY BIRTHDATE DEFAULT DATE('01-01-1850')
ADD COLUMN FLAGS BLOB(1M) DEFAULT BLOB(X'01')
ADD COLUMN PHOTO PICTURE DEFAULT BLOB(X'00')
|
Os valores padrão usam vários nomes de função ao especificar o padrão.
Como MEASURE é um tipo distinto baseado em INTEGER, a função MEASURE é usada.
O padrão da coluna HEIGHT poderia ter sido especificado sem a função, pois o tipo de fonte de MEASURE não é BLOB ou um tipo de dados datetime.
Como BIRTHDATE é um tipo distinto baseado em DATE, a função DATE é usada (BIRTHDATE não pode ser usada aqui).
Para as colunas FLAGS e PHOTO, o padrão é especificado usando a função BLOB, embora PHOTO seja um tipo distinto.
Para especificar um padrão para as colunas BIRTHDAY, FLAGS e PHOTO, uma função deve ser usada porque o tipo é um BLOB ou um tipo distinto que é originado
em um tipo de dados BLOB ou datetime.
Uma tabela chamada CUSTOMERS é definida com as seguintes colunas:
The default values use various function names when specifying the default.
Since MEASURE is a distinct type based on INTEGER, the MEASURE function is used.
The HEIGHT column default could have been specified without the function since the source type of MEASURE is not BLOB or a datetime data type.
Since BIRTHDATE is a distinct type based on DATE, the DATE function is used (BIRTHDATE cannot be used here).
For the FLAGS and PHOTO columns the default is specified by using the BLOB function even though PHOTO is a distinct type.
To specify a default for BIRTHDAY, FLAGS and PHOTO columns, a function must be used because the type is a BLOB or a distinct type that is sourced on a BLOB
or datetime data type.
A table called CUSTOMERS is defined with the following columns:
Column Name Data Type
BRANCH_NO SMALLINT
CUSTOMER_NO DECIMAL(7)
CUSTOMER_NAME VARCHAR(50)
|
Nesta tabela, a chave primária é composta pelas colunas BRANCH_NO e CUSTOMER_NO.
Para distribuir a tabela, você precisa criar uma chave de distribuição para a tabela.
A tabela deve ser definida em um espaço de tabela em um grupo de partição de banco de dados de nó único.
A chave primária deve ser um superconjunto das colunas da chave de distribuição e pelo menos uma das colunas da chave primária deve ser usada como a
chave de distribuição.
Faça BRANCH_NO a chave de distribuição da seguinte maneira:
In this table, the primary key is made up of the BRANCH_NO and CUSTOMER_NO columns.
To distribute the table, you need to create a distribution key for the table.
The table must be defined in a table space on a single-node database partition group.
The primary key must be a superset of the distribution key columns, and at least one of the columns of the primary key must be used as the distribution
key.
Make BRANCH_NO the distribution key as follows:
ALTER TABLE CUSTOMERS
ADD DISTRIBUTE BY HASH (BRANCH_NO)
|
Uma tabela remota EMPLOYEE foi criada em um sistema federado usando DDL transparente.
Altere a tabela remota EMPLOYEE para adicionar as colunas PHONE_NO e WORK_DEPT; além disso, inclua uma chave primária na coluna EMP_NO existente e na
nova coluna WORK_DEPT.
A remote table EMPLOYEE was created in a federated system by using transparent DDL.
Alter the remote table EMPLOYEE to add the columns PHONE_NO and WORK_DEPT; also, add a primary key on the existing column EMP_NO and the new column
WORK_DEPT.
ALTER TABLE EMPLOYEE
ADD COLUMN PHONE_NO CHAR(4) NOT NULL
ADD COLUMN WORK_DEPT CHAR(3)
ADD PRIMARY KEY (EMP_NO, WORK_DEPT)
|
Altere a tabela DEPARTMENT para adicionar uma dependência funcional FD1 e, em seguida, elimine a dependência funcional FD1 da tabela DEPARTMENT.
Alter the DEPARTMENT table to add a functional dependency FD1, then drop the functional dependency FD1 from the DEPARTMENT table.
ALTER TABLE DEPARTMENT
ADD CONSTRAINT FD1
CHECK ( DEPTNAME DETERMINED BY DEPTNO) NOT ENFORCED
ALTER TABLE DEPARTMENT
DROP CHECK FD1
|
Altere o valor padrão da coluna WORKDEPT na tabela EMPLOYEE para 123.
Change the default value for the WORKDEPT column in the EMPLOYEE table to 123.
ALTER TABLE EMPLOYEE
ALTER COLUMN WORKDEPT
SET DEFAULT '123'
|
Associe a política de segurança DATA_ACCESS à tabela EMPLOYEE.
Associate the security policy DATA_ACCESS with the table EMPLOYEE.
ALTER TABLE EMPLOYEE
ADD SECURITY POLICY DATA_ACCESS
|
Altere a tabela EMPLOYEE para proteger a coluna SALARY.
Alter the table EMPLOYEE to protect the SALARY column.
ALTER TABLE EMPLOYEE
ALTER COLUMN SALARY
SECURED WITH EMPLOYEESECLABEL
|
Suponha que você tenha uma tabela chamada SALARY_DATA definida com as seguintes colunas:
Assume that you have a table that is named SALARY_DATA that is defined with the following columns:
Column Name Data Type
----------- ---------
EMP_NAME VARCHAR(50) NOT NULL
EMP_ID SMALLINT NOT NULL
EMP_POSITION VARCHAR(100) NOT NULL
SALARY DECIMAL(5,2)
PROMOTION_DATE DATE NOT NULL
|
Altere esta tabela para permitir que os salários sejam armazenados em uma coluna DECIMAL (6,2), torne PROMOTION_DATE um campo opcional que pode ser
definido com o valor nulo e remova a coluna EMP_POSITION.
Change this table to allow salaries to be stored in a DECIMAL(6,2) column, make PROMOTION_DATE an optional field that can be set to the null value,
and remove the EMP_POSITION column.
ALTER TABLE SALARY_DATA
ALTER COLUMN SALARY SET DATA TYPE DECIMAL(6,2)
ALTER COLUMN PROMOTION_DATE DROP NOT NULL
DROP COLUMN EMP_POSITION
|
Adicione uma coluna denominada DATE_ADDED à tabela BOOKS.
O valor padrão para esta coluna é o carimbo de hora atual.
Add a column named DATE_ADDED to the table BOOKS.
The default value for this column is the current time stamp.
ALTER TABLE BOOKS
ADD COLUMN DATE_ADDED TIMESTAMP
WITH DEFAULT CURRENT TIMESTAMP
|
Altere a tabela com atributos de segurança de controle de acesso baseados em rótulo em uma tabela de consulta materializada.
As tabelas base tt1 e tt2 existem e foram criadas com o seguinte SQL:
Alter table with label-based access control security attributes into a materialized query table.
Base tables tt1 and tt2 exist and were created with the following SQL:
CREATE TABLE tt1
(c1 INT SECURED WITH C, c2 DB2SECURITYLABEL) SECURITY POLICY P;
CREATE TABLE tt2
(c3 INT SECURED WITH B, c4 DB2SECURITYLABEL) SECURITY POLICY P;
|
A tabela tt2 pode ser alterada para ser uma tabela de consulta materializada com o seguinte SQL:
Table tt2 can be altered to be a materialized query table with the following SQL:
ALTER TABLE tt2 ADD (SELECT * FROM tt1 WHERE c1 > 10)
DATA INITIALLY DEFERRED REFRESH DEFERRED;
|
A tabela tt2 torna-se uma tabela de consulta materializada com a política de segurança P. tt2.c3 tem etiqueta de segurança PB tt2.c4 tem etiqueta de
segurança PC e também é DB2SECURITYLABEL.
Table tt2 becomes a materialized query table with the secure policy P. tt2.c3 has security label P.B. tt2.c4 has security label P.C and it is also
DB2SECURITYLABEL.
|