备份表的动态变量名称

时间:2018-05-29 22:28:01

标签: sql sql-server backup

我正在尝试编写一个存储过程来备份一个表,但我不断得到:

  

Msg 402,Level 16,State 1,Line 9   数据类型varchar和datetime2在add运算符中不兼容。

     

Msg 402,Level 16,State 1,Line 15   数据类型varchar和datetime2在add运算符中不兼容。

我该如何解决这个问题?

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);

1 个答案:

答案 0 :(得分:0)

您必须将日期变量转换为字符串,以便连接它:

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