“ALTER TABLE IF EXISTS t1 RENAME TO t2” in HiveQL?

2019-09-15 09:12发布

问题:

I want to rename a Hive table if it exists, and not generate an error if it doesn't.

I need something like

ALTER TABLE IF EXISTS t1 RENAME TO t2;

but this doesn't run ("cannot recognize input near 'if' 'exists' 'rename' in alter table statement"), and neither do the variations that I've tried. This isn't covered in the docs (https://cwiki.apache.org/confluence/display/Hive/LanguageManual+DDL#LanguageManualDDL-RenameTable), maybe because it's not possible.

Does anyone know how to do this, or a workaround (e.g. try/catch, if it existed in Hive)?

I'm on Hive 1.2.

回答1:

IF EXIST clause does not work in Hive CLI as of now. You can write program something like below for condition checking.

public class HiveAlterRenameTo { private static String driverName = "org.apache.hadoop.hive.jdbc.HiveDriver";

public static void main(String[] args) throws SQLException {

  // Register driver and create driver instance
  Class.forName(driverName);

  // get connection
  Connection con = DriverManager.getConnection("jdbc:hive://localhost:10000/userdb", "", "");

  // create statement
  Statement stmt = con.createStatement();

  // execute statement
  Resultset res = stmt.executeQuery("SELECT count(*) FROM <Table_name> ;");


  if (res > 0) {
    // execute statement
  stmt.executeQuery("ALTER TABLE employee RENAME TO emp;");
    System.out.println("Table Renamed Successfully");

  }
  else {
        System.out.println("Table Not exist");
  }
  con.close();

}



标签: hadoop hive