在本教程中,您将学习如何使用oracle alter table add
列语句向表中添加一列或多列。
要将新列添加到表中,请按如下所示使用alter table语句:
alter table table_name
add column_name data_type constraint;
在上面这个语句中,
alter table
子句之后指定要添加新列的表的名称。请注意,不能添加表中已经存在的列; 这样做会导致错误。 另外,
alter table add
列语句在表的末尾添加新列。 oracle没有提供直接的方法来允许您像其他数据库系统(如mysql)那样指定新列的位置。
如果想要添加多个列,请使用以下语法:
alter table table_name
add (
column_name_1 data_type constraint,
column_name_2 data_type constraint,
...
);
在这个语法中,用逗号分隔两列。
下面来创建一个名为members
的表。参考以下sql语句 -
-- 12c语法
create table members(
member_id number generated by default as identity,
first_name varchar2(50),
last_name varchar2(50),
primary key(member_id)
);
以下语句将一个名为birth_date
的新列添加到members
表中:
alter table members
add birth_date date not null;
在这个例子中,birth_date
列是一个date
列,它不接受null
。
假设想记录一行的创建和更新的时间。那么可以再添加两列created_at
和updated_at
,如下所示:
alter table
members add(
created_at timestamp with time zone not null,
updated_at timestamp with time zone not null
);
created_at
和updated_at
列的数据类型是timestamp with time zone
。 这些列也不接受null
。
要检查表中是否存在列,可以从user_tab_cols
视图查询数据。 例如,以下语句将检查members
表是否具有first_name
列。
select
count(*)
from
user_tab_cols
where
column_name = 'first_name'
and table_name = 'members';
当想在添加表之前检查列中是否存在列时,此查询就派上用场了。
例如,下面的pl/sql块在添加之前检查members
表是否有effective_date
列。
set serveroutput on size 1000000
declare
v_col_exists number
begin
select count(*) into v_col_exists
from user_tab_cols
where column_name = 'effective_date'
and table_name = 'members';
if (v_col_exists = 0) then
execute immediate 'alter table members add effective_date date';
else
dbms_output.put_line('the column effective_date already exists');
end if;
end;
/
如果第一次执行该块,那么effective_date
列将被添加到members
表的末尾。 但是,一旦从第二次执行它,将看到以下消息:
the column effective_date already exists
这与上面编写的程序的预期一致。
在本教程中,您已学习如何使用oracle alter table add
列语句将一列或多列添加到现有表。