How to generate table name by datetime?

笑着哭i 提交于 2021-02-11 00:32:14

问题


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?


回答1:


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

When you're happy with the logic and want to execute the command, just swap the comments between PRINT and EXEC.




回答2:


I am not sure if you are looking for this.

DECLARE @date datetime, @CMD varchar(1000);
SET @date = CONVERT(VARCHAR(10), GETDATE(), 105)
SET @cmd = 'SELECT * INTO [dbo.T_TABLE_Backup_' + replace(cast(@date as varchar(11)),' ','_')+'] FROM dbo.T_TABLE'
print @cmd;


来源:https://stackoverflow.com/questions/11110775/how-to-generate-table-name-by-datetime

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