修改已经存在的表:


alter table



Alter table 语句允许用户改变现有表的结构。用户可以增加列/分区,表本身重命名。





1) 增加分区 Add Partitions:



ALTER TABLE table_name ADD partition_spec [ LOCATION 'location1']partition_spec [ LOCATION 'location2' ]



其中partition_spec的格式为:PARTITION (partition_col =partition_col_value, partition_col =partiton_col_value, ...)



用户可以用





alter table test_partition add partition (dt='2012-03-06')location'/home/zhangxin/hive/test_hive.txt';





2) 删除分区 drop Partition:



ALTER TABLE table_name DROP partition_spec, partition_spec,...



用户可以用





alter table test_partition drop partition (dt='2012-03-06')





3) 对表进行重命名 rename to:



ALTER TABLE table_name RENAME TO new_table_name



这个命令可以让用户为表更名。数据所在的位置和分区名并不改变。换而言之,老的表名并未“释放”,对老表的更改会改变新表的数据。



alter table test_partition rename to new_test_partition;





4) 对表中的某一列进行修改,包括列的名称/列的数据类型/列的位置/列的注释



ALTER TABLE table_name CHANGE [COLUMN] col_old_name col_new_namecolumn_type[COMMENT col_comment] [FIRST|AFTER column_name]



这个命令可以允许用户修改一个列的名称、数据类型、注释或者位置



create table test_col_change (a int,b int, c int);





修改列的名称,后面一定要加上数据类型:



ALTER TABLE test_col_change CHANGE a a1 INT; 将 a 列的名字改为 a1.





ALTER TABLE test_col_change CHANGE a a1 STRING AFTER b; 将 a 列的名字改为 a1,a 列的数据类型改为string,并将它放置在列 b 之后。新的表结构为: b int, a1 string, c int.





ALTER TABLE test_col_change CHANGE b b1 INT FIRST; 会将 b 列的名字修改为b1, 并将它放在第一列。新表的结构为: b1 int, a string, c int.





注意:对列的改变只会修改Hive 的元数据,而不会改变实际数据。用户应该确定保证元数据定义和实际数据结构的一致性。





5) 添加/替换列Add/ReplaceColumns



ALTER TABLE table_name ADD|REPLACE COLUMNS (col_name data_type [COMMENTcol_comment],...)



ADD COLUMNS 允许用户在当前列的末尾增加新的列,但是在分区列之前。



alter table test_col_change add columns (d int);



describe test_col_change;



OK



a1 int 



b1 string 



c int 



d int 





REPLACE COLUMNS 删除以后的列,加入新的列。只有在使用 native 的SerDE(DynamicSerDeorMetadataTypeColumnsetSerDe)的时候才可以这么做。



alter table test_col_change replace columns (c int);



describetest_col_change; 



OK



c int 





6) 修改表的属性Alter Table Properties:



ALTER TABLE table_name SET TBLPROPERTIES table_properties 



table_properties: : (property_name = property_value, property_name=property_value, ... )






alter table test_col_change set tblproperties ('key1'='value1');



可以通过





7) 修改表的序列化和反序列化属性:



ALTER TABLE table_name SET SERDE serde_class_name [WITHSERDEPROPERTIESserde_properties]



ALTER TABLE table_name SET SERDEPROPERTIES serde_properties



serde_properties: : (property_name = property_value, property_name=property_value, ... )





这个命令允许用户向





8) 修改表的文件存储格式组织方式:



ALTER TABLE table_name SET FILEFORMAT file_format



ALTER TABLE table_name CLUSTERED BY (col_name, col_name, ...) [SORTEDBY(col_name, ...)] INTO num_buckets BUCKETS



这个命令修改了表的物理存储属性。