问题
At the moment I have to rerun data selection query every month, where I create one base table. This table is named something like MyDB.MyTable_Current_Date
, so for today that would be MyDB.MyTable_201811
using YYYYMM date format.
Instead of having to set the name manually (using ctrl + h), I would like this to be done automaticaly. My goal is that I can open the SQL and run the query where the the table that is created is MyTable_YYYYMM
.
Note: eventually I want to also let the SQL run automatically every month, but for now this is a nice first step for my understanding.
I made the below stored procedure. The problem is that if I want to do an alter table
or insert into
statement, I cannot (or don't know how to) refer to the table that was created.
REPLACE PROCEDURE DB.table_yymm
(
IN db_name VARCHAR(128),
tbl_name VARCHAR(128)
)
BEGIN
DECLARE create_name VARCHAR(261)
;
DECLARE sql_stmt VARCHAR(600)
;
SET create_name = db_name || '.' || tbl_name || CAST(
(CURRENT_DATE (FORMAT 'yymm'))
AS CHAR(4)
)
;
SET sql_stmt = 'CREATE TABLE ' || create_name || ' (testvar char(1))' || ';' ;
EXECUTE IMMEDIATE sql_stmt;
END;
CALL prd_work_lm.table_yymm('My_DB', 'My_Table')
Should I do this using a stored procedure, or using a user defined function?
It would be ideal if I could simply refer to some function, for example:
CREATE TABLE DB.My_UDF(<My_DB>, <My_Table_Name>)
Could you help me by providing an example of a code sample?
回答1:
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;
来源:https://stackoverflow.com/questions/53297953/how-can-i-create-a-table-with-a-dynamic-name-based-on-current-date-and-referen