SQL Server中的动态查询执行

时间:2017-07-21 10:14:02

标签: sql sql-server dynamic-sql

我创建了一个存储过程来备份多个文件中的任何数据库。

这是我的存储过程:

ALTER PROCEDURE [dbo].[BackupJob]
(
    @FileGroup      NVARCHAR(1000),
    @Path   NVARCHAR(MAX),
    @NoOfFile INT
)
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @SQLQuery AS NVarChar(MAX)
    DECLARE @SQLSubQuery AS NVarChar(MAX)
    DECLARE @ParamDefintion AS NVarChar(2000)
    DECLARE @Err Int
    DECLARE @i Int
    DECLARE @Backup_Name NVarChar(max)
    DECLARE @DB_Name NVarChar(max)

    SELECT @DB_Name = DB_NAME()
    SET @i=1;

    -- SELECT statements for procedure here
    SET @SQLQuery = '
    BACKUP DATABASE ['+@DB_Name+'] FILEGROUP = '''+@FileGroup+''' TO  '

    PRINT (@SQLQuery)

    WHILE (@i <= @NoOfFile)
    BEGIN
        SELECT @Backup_Name = @Path + '\'+ DB_NAME()+ '_' + @FileGroup +'_' + CONVERT(VARCHAR(10), GETDATE(), 112)+ '_' + CONVERT(nvarchar,@i)+'.bak'

        SET @SQLSubQuery =ISNULL(@SQLSubQuery,'') + ' DISK = '''+ @Backup_Name + ''''

        IF(@i<@NoOfFile)
        BEGIN
            SET @SQLSubQuery =@SQLSubQuery + ','
        END

        SET @i = @i + 1
    END

    SET @SQLQuery =  @SQLSubQuery + ' WITH CHECKSUM'

    PRINT (@SQLQuery)
    EXECUTE (@SQLQuery)

    SET @Err = @@Error
    RETURN (@Err)
END

如果我打印存储过程并执行它,它工作正常,但如果我执行这样的存储过程:

exec [BackupJob] 'PRIMARY', 'E:\trybackup',2

我收到错误:

  

Msg 102,Level 15,State 1,Line 1
  &#39; =&#39;附近的语法不正确。

对此有何建议?

由于

1 个答案:

答案 0 :(得分:0)

再试一次:

ALTER PROCEDURE [dbo].[BackupJob]
(
    -- Add the parameters for the stored procedure here
    @FileGroup      NVARCHAR(1000),
    @Path   NVARCHAR(MAX),
    @NoOfFile INT
)
AS
BEGIN
    DECLARE @SQLQuery AS NVarChar(MAX)
    DECLARE @SQLSubQuery AS NVarChar(MAX)
    DECLARE @ParamDefintion AS NVarChar(2000)
    DECLARE @Err Int
    DECLARE @i Int
    DECLARE @Backup_Name NVarChar(max)
    DECLARE @DB_Name NVarChar(max)


    SELECT @DB_Name = DB_NAME()
    SET @i=1;

    -- SELECT statements for procedure here
    SET @SQLQuery = '
    BACKUP DATABASE ['+@DB_Name+'] FILEGROUP = '''+@FileGroup+''' TO  '

    While( @i<=@NoOfFile)
    BEGIN
        SELECT @Backup_Name = @Path + '\'+ DB_NAME()+ '_' + @FileGroup +'_' + CONVERT(VARCHAR(10), GETDATE(), 112)+ '_' + CONVERT(nvarchar,@i)+'.bak'

        SET @SQLSubQuery =ISNULL(@SQLSubQuery,'') + ' DISK = '''+ @Backup_Name + ''''

        IF(@i<@NoOfFile)
        BEGIN
        SET @SQLSubQuery =@SQLSubQuery + ','
        END
    SET @i = @i + 1
    END

    SET @SQLQuery = @SQLQuery +  @SQLSubQuery   + ' WITH CHECKSUM'
    print(@SQLQuery)
    exec (@SQLQuery)

    SET @Err = @@ERROR
    RETURN (@Err)
    END