Help with Backup TSQL command.

  • Hi,

    I am trying to use backup command to backup to disk.

    I have a temporary table that stores the database names in "name" column

    Temp table

    Name

    db1

    db2

    db3

    db5

    I want to check if the values match then

    declare @db_name nvarchar(max)

    if exists( select name from @TempTable)

    backup database @db_name to disk =N'C:\Temp\'+@db_name+'.bak'

    any help would be much appreciated.

    Thanks

  • check if the values match what?

    Currently you are never populating @dbname,also specifying it as nvarchar(max) seems overkill, have you got database names that long?

    This is an example where a cursor to loop through the databases to backup would work well, as the time taken to backup the databases is by far the longest part of the query.

    you can build up a list of databases from sys.databases.

    ---------------------------------------------------------------------

  • I think the issue is the concatenation for the backup path. When I do the concatenation I get an error, when I move the concatenation out and just use a variable there it works.

    This works:

    DECLARE @DBNAME NVARCHAR(100)

    DECLARE @path NVARCHAR(200)

    SET @DBNAME = N'master'

    SET @path = N'C:\Backups\' + @dbname + N'.bak'

    BACKUP DATABASE @DBNAME TO DISK = @path

  • Hi,

    Thank you for suggestions. the concatenation is not a major issue right now. but what I wanted to do is that

    pass column values to @db_name variable and use this variable to run backups.

    that's where I am stuck with.

  • I assume you wanted to backup all the databases that existed in the temp table.

    I would suggest using a cursor as explained in this article

    http://www.mssqltips.com/tip.asp?tip=1070

    You may change the table name to be your temp table instead of using master.dbo.sysdatabases


    Bru Medishetty

    Blog -- LearnSQLWithBru

    Join on Facebook Page Facebook.comLearnSQLWithBru

    Twitter -- BruMedishetty

Viewing 5 posts - 1 through 4 (of 4 total)

You must be logged in to reply to this topic. Login to reply