备份的动态变量名称 table

Dynamic Variable Name for backup table

我正在尝试编写存储过程来备份 table,但我不断收到:

Msg 402, Level 16, State 1, Line 9 The data types varchar and datetime2 are incompatible in the add operator.

Msg 402, Level 16, State 1, Line 15 The data types varchar and datetime2 are incompatible in the add operator.

我该如何解决这个问题?

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @CreateDynamicSQL nvarchar(1000);
DECLARE @CopyDynamicSQL nvarchar(1000);

SET @CreateDynamicSQL='CREATE TABLE [dbo].[paul_AccountContact_Backup_'+@SYSDATETIME+'](
    [AccountID] [int] NOT NULL,
    [ContactID] [int] NOT NULL
) ON [PRIMARY]
GO'

SET @CopyDynamicSQL='select * into [dbo].[paul_AccountContact_Backup_'+@SYSDATETIME+'] from paul_AccountContacts'

EXEC(@CreateDynamicSQL);
EXEC(@CopyDynamicSQL);

您必须将日期变量转换为字符串才能连接它:

SET @CreateDynamicSQL='CREATE TABLE [dbo].[paul_AccountContact_Backup_' 
+ convert(varchar(20), @SYSDATETIME, <Format>) + '](

格式参数的文档:
https://docs.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql?view=sql-server-2017