![](/img/trans.png)
[英]How can I create a table with a dynamic name (based on current_date) and reference to it in INSERT statements?
[英]Get week from current_date and create a table with dynamic name in SQL
我每周运行一个特定的查询,创建一个所需数据的每周表。
表名的格式如下所述
由于这是一个重复的任务,我想安排这个查询,以便它会在特定周的每个星期一自动运行,以获得前一周的数据。
我面临的问题是,我不知道如何在每周运行查询时动态更改我的表名。
因此,当我下次运行查询时,它应该自动创建一个名为db_name.subscriptions_wk32
的表。 我可以从weekofyear('2019-08-05')
获得价值32,但不知道如何把它放在表名中
目前我写的如下
CREATE TABLE db_name.subscriptions_wk30 AS -- a hardcoded name
SELECT *
FROM ..........
我想要的是
CREATE TABLE db_name.subscriptions_wkCAST(weekofyear('2019-08-05') AS varchar) -- a dynamic name
SELECT *
FROM ..........
这将导致
CREATE TABLE db_name.subscriptions_wk32 SELECT * FROM ..........
PS我使用Hive / Hue作为RDBMS
无法在查询本身中计算表名,但可以将参数传递给脚本。 您可以在shell中计算参数并从shell执行脚本:
#You can provide date:
varDate=2019-08-05
#And calculate weekyear
weeknumber=$(date --date=${varDate} +%V)
echo "${weeknumber}"
#returns 32
#Or calculate current date weekyear
weeknumber=`date +%V`
#Or calculate previous week date
weeknumber="$(date -d "7 days ago" +"%V")"
#And call hive script like this:
hive -e "CREATE TABLE db_name.subscriptions_wk${weeknumber} -- parametrized name suffix
SELECT *
FROM ...
"
或者您可以在hive命令行中使用-hivevar
参数来调用脚本文件( -f
选项),假设已经像以前一样计算了weeknumber
:
hive -hivevar weeknumber="$weeknumber" -f script_file_name
您可以使用下面的shell创建动态每周表,并可以使用oozie scheduler或作为cron作业安排它在每个星期一运行。
#!/bin/bash
echo "Executing the hive query - get current week and store it in shell variable"
#current_week=$(hive -e "select weekofyear(current_date);")
#echo $current_week
previous_week=$(hive -e "select weekofyear(date_sub(current_date, 7));")
echo $previous_week
hive --hiveconf dbname=test_dev_db --hiveconf weekname=$previous_week -f hdfs://xxx.host.com:8020/user/xxx/dev/hadoop/hivescripts/createweektable.hql
echo "Executing the hive query - ends"
hive (test_dev_db)> desc test_dev_db.subscriptions_wk31;
OK
user_id int
country string
last_modified_date date
Time taken: 0.345 seconds, Fetched: 3 row(s)
更新 -这是您在hql脚本中引用shell变量的方法。
CREATE TABLE ${hiveconf:dbname}.subscriptions_wk${hiveconf:weekname}
row format delimited
fields terminated by '|'
STORED AS ORC
AS select * from test_dev_db.test_data;
不要这样做! 拥有多个具有相同结构的并行表是一个非常糟糕的主意。
相反,有一个表db_name.subscriptions
并添加一个指定周的列 - 可能是一周的第一个星期一或最后一个星期日。
然后,不是创建单独的表,而是每周插入行。
您将发现拥有单个表的优势:
where
子句(可以参数化)而不是更改from
子句(不可以),可以在任何一周运行在报表上运行的SQL语句。 如果每周产生一个非常重要的行数,那么在同一个表中创建周分区非常有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.