How to generate table name by datetime?(如何按日期时间生成表名?)
问题描述
我意识到这在语法上很糟糕,但我认为它在某种程度上解释了我正在尝试做的事情.本质上,我有一个批处理作业,每天早上要在一个小表上运行,作为规范的一部分,我需要在每次加载之前创建一个可以通过报告访问的备份.
I realize this is syntactically bad but I figure it somewhat explains what I'm trying to do. Essentially, I have a batch job that is going to run each morning on a small table and as a part of the spec I need to create a backup prior to each load that can be accessed by a report.
到目前为止我所拥有的是:
What I have so far is:
select *
into report_temp.MSK_Traffic_Backup_ + getdate()
from property.door_traffic
我怎样才能实现这个功能,或者我应该考虑用更好的方式来做这个吗?
How can I make this function or should I consider doing this a better way?
推荐答案
DECLARE @d CHAR(10) = CONVERT(CHAR(8), GETDATE(), 112);
DECLARE @sql NVARCHAR(MAX) = N'select *
into report_temp.MSK_Traffic_Backup_' + @d + '
from property.door_traffic;';
PRINT @sql;
--EXEC sys.sp_executesql @sql;
现在,您可能还想添加一些逻辑,使脚本在一天内运行多次时不会出错,例如
Now, you might also want to add some logic to make the script immune to error if run more than once in a given day, e.g.
DECLARE @d CHAR(10) = CONVERT(CHAR(8), GETDATE(), 112);
IF OBJECT_ID('report_temp.MSK_Traffic_Backup_' + @d) IS NULL
BEGIN
DECLARE @sql NVARCHAR(MAX) = N'select *
into report_temp.MSK_Traffic_Backup_' + @d + '
from property.door_traffic;';
PRINT @sql;
--EXEC sys.sp_executesql @sql;
END
当您对逻辑感到满意并想要执行命令时,只需在 PRINT
和 EXEC
之间交换注释即可.
When you're happy with the logic and want to execute the command, just swap the comments between PRINT
and EXEC
.
这篇关于如何按日期时间生成表名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何按日期时间生成表名?


基础教程推荐
- 表 './mysql/proc' 被标记为崩溃,应该修复 2022-01-01
- oracle区分大小写的原因? 2021-01-01
- 二进制文件到 SQL 数据库 Apache Camel 2021-01-01
- mysql选择动态行值作为列名,另一列作为值 2021-01-01
- 什么是 orradiag_<user>文件夹? 2022-01-01
- 如何在 SQL 中将 Float 转换为 Varchar 2021-01-01
- 在 MySQL 中:如何将表名作为存储过程和/或函数参数传递? 2021-01-01
- 如何根据该 XML 中的值更新 SQL 中的 XML 2021-01-01
- MySQL 中的类型:BigInt(20) 与 Int(20) 2021-01-01
- 在多列上分布任意行 2021-01-01