How can I create a table with a dynamic name (based on current_date) and reference to it in INSERT statements?

前提是你 提交于 2019-12-02 04:09:59

Instead of initially creating the new table MyDB.MyTable_201811 and use it throughout your script you can simply create a table with a known name, e.g. MyDB.MyTable_000000. Now this name is used and renamed as last step.

This is a slight variation of an existing SP to rename a table from '..._000000' to '..._yyyymmdd':

REPLACE PROCEDURE rename_table_to_yyyymm
(
  IN db_name VARCHAR(128) CHARACTER SET Unicode,
  IN tbl_name VARCHAR(128) CHARACTER SET Unicode,
  OUT msg VARCHAR(600) CHARACTER SET Unicode
) SQL SECURITY INVOKER
BEGIN
   DECLARE old_name VARCHAR(261)  CHARACTER SET Unicode;
   DECLARE new_name VARCHAR(261)  CHARACTER SET Unicode;

   DECLARE sql_stmt VARCHAR(600)  CHARACTER SET Unicode;

   SET old_name  = '"' || Coalesce(NullIf(db_name,''), DATABASE) || '"."' 
                       || Coalesce(tbl_name, '') || '"';

   SET new_name  = '"' || Coalesce(NullIf(db_name,''),DATABASE) || '"."' 
                       || Trim(Trailing '0' FROM tbl_name)-- remove '000000' at the end of the table name
                       || '_' || To_Char(Current_Date, 'YYYYMM') || '"';

   SET sql_stmt = 'RENAME TABLE ' || old_name || ' AS ' || new_name || ';'; 

   EXECUTE IMMEDIATE sql_stmt;

   SET msg = ' Table ' || old_name || ' renamed to ' || new_name;

END;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!