Schedule A Scripted Restore On 2005 Express From .bak File.
Oct 28, 2007
Hi i have an web app demo that allows users to add info and change attributes within a SQL 2005 Express DB. I'd like to restore a clean copy of this database every couple of hours from a .bak file using a Windows scheduled task on the server. Has anyone got a .sql script for database restoration that i could use and call using a .cmd script file? Thanks.
FYI: I've posted this on a couple of forums and haven't gotten any response. I hope someone here can help since this is way past due.
First I'll give a little background on our situation.
Log Shipping and Replication are out, so I am scripting a backup locally, an xcopy to a remote box, and then a restore.
In the early stages of this, I'm trying to do 3 databases. 2 of them work fine alone. It's when I add the 3rd one that I have a problem. I noticed that in the 2nd stored procedure that I probably need to take out the WITH REPLACE if I'm dropping it beforehand as well. I don't have time to test it on this box until later tonight. I don't think that's the issue because it was doing the same thing before I added the drop. I'm overwriting the .txt file so I don't have the exact error that it's giving. I believe it's something similar to "Server: Msg 11, Level 16, State 1, Line 0 General network error. Check your network documentation." I believe it also said [SQLSTATE 42000].
Now for the code. Props to Tara and the code she's put online.
Any help would be appreciated and I'll be glad to help answer questions related to what I've got.
CREATE PROC sp_backup_user_dbs3 AS SET nocount ON DECLARE @Now CHAR(14) -- current date in the form of yyyymmddhhmmss DECLARE @cmd SYSNAME -- stores the dynamically created DOS command DECLARE @Result INT -- stores the result of the dir DOS command DECLARE @RowCnt INT -- stores @@ROWCOUNT DECLARE @DBName SYSNAME DECLARE @filename VARCHAR(200) -- stores the path and file name of the BAK file DECLARE @loglogical VARCHAR(1000) DECLARE @datalogical VARCHAR(1000) DECLARE @restoreData VARCHAR(255) DECLARE @restoreLog VARCHAR(255) DECLARE @backupFile VARCHAR(255) DECLARE @physicalNameData VARCHAR(255) DECLARE @physicalNameLog VARCHAR(255) DECLARE @physicalNameDataStripped VARCHAR(255) DECLARE @physicalNameLogStripped VARCHAR(255) DECLARE @ExecStr NVARCHAR(4000) DECLARE @strSQL VARCHAR(1000) DECLARE @restoreToDataDir VARCHAR(255) DECLARE @restoreToLogDir VARCHAR(255) DECLARE @path VARCHAR(100) SET @path = 'I:ackupMoveTo14'
--we need to delete all the old backup files from the I:ackupMoveTo14 folder -- Build the del command SELECT @cmd = 'del ' + @path + '*.BAK' + ' /Q /F' --PRINT @cmd EXEC master..xp_cmdshell @cmd, NO_OUTPUT
CREATE TABLE #whichdatabase ( dbname SYSNAME NOT NULL )
INSERT INTO #whichdatabase ( dbname ) SELECT [name] FROM master.dbo.sysdatabases WHERE [name] IN ( 'db1', 'db2') ORDER BY [name] -- Get the database to be backed up SELECT TOP 1 @DBName = dbname FROM #whichdatabase SET @RowCnt = @@ROWCOUNT -- Iterate throught the temp table until no more databases need to be backed up WHILE @RowCnt <> 0 BEGIN SELECT @filename = @Path + '' + @DBName + '.BAK' BEGIN backup log @dbname WITH truncate_only END
-- Backup the database BACKUP database @DBName TO disk = @filename
DELETE FROM #whichdatabase WHERE dbname = @DBName
-- Get the database to be backed up SELECT TOP 1 @DBName = dbname FROM #whichdatabase SET @RowCnt = @@ROWCOUNT -- Let the system rest for 5 seconds before starting on the next backup WAITFOR delay '00:00:05' END
DROP TABLE #whichdatabase SET nocount OFF BEGIN SET @cmd = '' SET @cmd = 'xcopy I:ackupMoveTo14*.BAK \RemoteServer /C /Y' EXEC master.dbo.xp_cmdshell @cmd END BEGIN
EXEC [RemoteServer].master..usp_restoreDbsFromDir2 END RETURN 0 GO
3rd Step(the code for the usp_restoreDbsFromDir2 on the remote server):
-- Get files sorted by date SET @cmd = 'dir ' + @restoreDir + '*.BAK /OD'
CREATE TABLE #Dir (DirInfo VARCHAR(7000) ) -- Stores the dir results CREATE TABLE #BackupFiles (BackupDate varchar(10), BackupFileName nvarchar(1000) ) -- Stores only the data we want from the dir CREATE TABLE #RestoreFileListOnly ( LogicalName nvarchar(128), PhysicalName nvarchar(260), Type char(1), FileGroupName nvarchar(128), [Size] numeric(20,0), [MaxSize] numeric(20,0) )
INSERT INTO #Dir EXEC master.dbo.xp_cmdshell @cmd
INSERT INTO #BackupFiles SELECT SUBSTRING(DirInfo, 1, 10), SUBSTRING(DirInfo, LEN(DirInfo) - PATINDEX('% %', REVERSE(DirInfo)) + 2, LEN(DirInfo)) FROM #Dir WHERE ISDATE(SUBSTRING(DirInfo, 1, 10)) = 1 AND DirInfo NOT LIKE '%<DIR>%'
-- Get the newest file SELECT TOP 1 @bkpFile = BackupFileName FROM #BackupFiles ORDER BY BackupDate DESC
SET @rowCnt = @@ROWCOUNT
-- Iterate throught the table until no more databases need to be backed up WHILE @RowCnt <> 0 BEGIN
SET @cmd = @restoreDir + @bkpFile
INSERT INTO #RestoreFileListOnly EXEC('RESTORE FILELISTONLY FROM DISK = ''' + @cmd + '''')
--get the dbname from the bkpFile name --SET @strSQL = CHARINDEX('_db_', @bkpFile) --SET @dbname = LEFT(@bkpFile, @strSQL - 1)
SET @backupDisk = @restoreDir + @bkpFile SELECT @datalogical = LogicalName FROM #RestoreFileListOnly WHERE Type = 'D' SELECT @loglogical = LogicalName FROM #RestoreFileListOnly WHERE Type = 'L' SELECT @PhysicalDataPath = PhysicalName FROM #RestoreFileListOnly WHERE Type = 'D' SELECT @PhysicalLogPath = PhysicalName FROM #RestoreFileListOnly WHERE Type = 'L'
SELECT @strSQL = 'alter database ' + @dbname + ' set offline with rollback immediate' --alter database MyDatabase set offline with rollback immediate --PRINT @strSQL EXEC (@strSQL)
SELECT @strSQL = 'DROP database ' + @dbname --alter database MyDatabase set offline with rollback immediate --PRINT @strSQL EXEC (@strSQL)
How do I schedule a backup with SQL Server 2005 Express. When I right-click a database and choose Tasks -> Back Up... I don't get the option to schedule the backup. How do I do?
can anyone explain me how can i make a DB backup in sql express 2005 ? The sql express instance and my web aplication are running on the same server. I need a script for directly execute it (and if possible also to restore the DB ) from my web aplication.
other question: any idea how can i tell to sql express to do the backup automatically every day?
From everything I'm reading, I shouldn't be getting this error in 2005: Too many backup devices specified for backup or restore; only 64 are allowed. RESTORE HEADERONLY is terminating abnormally. (Microsoft SQL Server, Error: 3205) I have both SQL Server 2000 and SQL Server 2005 (Express) on same dev box, have loaded SP 4 for 2000, I'm trying to restore this in 2005. Why am I still getting this error? Help is appreciated greatly. Thanks. Sheryl
I have a database backup from Server Express 2005 that I want to restore to SQL Server 2000. I keep getting an error message saying it was created a newer version and wont work. Is there a workaround to this.
I am moving my data base from one computer to a new one. I placed the .bak file in the backup folder on the new computer (Windows Vista). I keep getting these errors I have checked the security settings and my user account has full privledges. I added my windows login to the SQL Administrators as well.
Here is the error msg.: TITLE: Microsoft SQL Server Management Studio Express ------------------------------
Restore failed for Server 'laptopsqlexpress'. (Microsoft.SqlServer.Express.Smo)
For help, click: http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&ProdVer=9.00.3042.00&EvtSrc=Microsoft.SqlServer.Management.Smo.ExceptionTemplates.FailedOperationExceptionText&EvtID=Restore+Server&LinkId=20476
System.Data.SqlClient.SqlError: The operating system returned the error '5(Access is denied.)' while attempting 'RestoreContainer::ValidateTargetForCreation' on 'c:Program FilesMicrosoft SQL ServerMSSQL.1MSSQLPRM - 6009757.mdf'. (Microsoft.SqlServer.Express.Smo)
For help, click: http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&ProdVer=9.00.3042.00&LinkId=20476
------------------------------ BUTTONS:
OK ------------------------------ What am I missing?
I'm currently working on a project which uses a SQL Express 2005 database. I want to be able to setup SQL Express from my C# program so that it can perform backups to a specified path location at the requested interval itself. This would free up my program from having to manage the backups. Just wanted to know if this is possible?
Also, when the current database becomes corrupt will SQL Express perform the restore for the user automatically, instead of them having to manually request a restore? I realize that it might not be able to handle the restores in the same way as backups, but I figured I'd at least ask.
I am trying to schedule a daily task to restore the latest backup from a BackupDevice that contains multiple backups. The command to restore is "Load DBName from BackupDevice". Does anyone know how to restore the most current backup from the Backup device?
I am trying to restore a database backed up using SQL Server 2005 Express Edition to a server using MSDE. I get an error 3205 "Too many backup devices specified...64 max..."
Hi,Did anyone successfully set up a local package to first ftp a db.bakand second perform an automated db restore?I need to perform an automated task, which ftp nightly backup file toanother server and then restore onto a database and leave the databasein read-only mode for additional transaction logs restore during theday.Can someone help and provide the procedures on how to do that?Thanks in advance.
every time I try to verify the backup file I get the error:
backup set on file '1' is not valid (translated from italian).
this is my backup script:
BACKUP DATABASE [ahr_sistema] TO DISK = N'C:ProgrammiMicrosoft SQL ServerMSSQL.1MSSQLBackupahr_sistemaahr_sistema_backup_1.bak' WITH FORMAT, INIT, NAME = N'ahr_sistema-Completo Database Backup', SKIP, NOREWIND, NOUNLOAD, STATS = 10
GO
declare @backupSetId as int
select @backupSetId = position from msdb..backupset where database_name=N'ahr_sistema' and backup_set_id=(select max(backup_set_id) from msdb..backupset where database_name=N'ahr_sistema' )
if @backupSetId is null begin raiserror(N'Verifica non riuscita. Impossibile trovare le informazioni di backup per il database ''ahr_sistema''.', 16, 1) end
RESTORE VERIFYONLY FROM DISK = N'C:ProgrammiMicrosoft SQL ServerMSSQL.1MSSQLBackupahr_sistemaahr_sistema_backup_1.bak' WITH FILE = @backupSetId, NOUNLOAD, NOREWIND
I am trying to restore database from network drive but sql server 2005 express is giving error "system.data.sqlclient.sqlErroratabase <dbname> cannot be opened due to inaccessible files or insufficient memory or disk space (microsoft.sqlserver.express.smo)." But when I restore database from "C:" or local drive it alows to do so. Can anyone help.
Hi at all, first post....first help :P . I hope to help another one (basing on my knowledge) in the next future :)
I'm a beginner dbadmin and I'm looking for help regarding a strange fact relative SQL Server 2005 :)
I migrated a medium(3,5GB) database from sql server 2000 to sql server 2005. I made a backup in sql server 2000 (it has generated a 3,5GB BAK FILE) and I restored it in sql server 2005 on another server. (I didn't checked data file size).
I configured (with wizard) a maintenance plan on new sql server 2005 with these steps (in this order): (tellme if the order of the steps is wrong :))
1) check db 2) rebuild index 3) reorganize indexes 4) update statistics (all table and all views)
I planned the maintenance plan on 3a.m. and I went home.
Next day I found that data file (MDF) on sql server 2005 was 22GB large!! I made a shrink DB but there wasn't free space to erase. It seems there are 22GB of data. (the data inside is the same of the sql 2000 server..same records same table...identical, non change of data in the meanwhile)
How is it possible? What am I doing wrong? I don't understand what can caused the growth of the file, the maintenance plan or the restore? (unfortunately....I didn't checked size after restore...I checked it only the next day). May be the statistics? (there wasn'int update statistics job on old maintenance plan on sql server 2000)
I'm working on a restore procedure for the case where all MDF filesare missing, but the LDF files are all intact. A full backup is doneevery 24 hours, and a log backup is done every 3 hours. Afterrestoring the last full + log backups, is it at all possible to usethe LDF files to recover data from that point up to a newer point intime?I've found a post which explains how to do this on SQL Server 2000<http://groups.google.com/group/comp...s.ms-sqlserver/browse_thread/thread/3ef5c7cbc0a83334/f3b0c70811d35ed7>, but step 4fails with the following error message:BACKUP LOG cannot be performed because there is no current databasebackup.
A full database backup file was created and placed in my C:Program filesMicrosoft SQL ServerMSSQL.1MSSQLBackup folder. In attempting to restore the file using "Restore Database", I get the following error: System.Data.SqlClient.SqlError: Directory lookup for the file "d:Microsoft SQL ServerMSSQLdataworkspace.mdf" failed with the operating system error 3 (The system could not find the file path specified.).
I need to schedule SQL Express backup from ASP Page. I was trying to use SQLDMO to schedule jobs but found that SQL Agent is not supported in Sql Express. I tried to use Scheduler.SchedulingAgent.1 to add task in schedular but getting Invalid class string error. Schedular dll is only supported in site server. What would be the best solution for me to schedule back for SQL Express??
Hi Friends,I have installed SQL server 2005 Express Edition and SQL Server managementI have a SQL server 2000 db backup file. I try create a new database in my SQL server 2005 express Edition and try restore that backup file from device, it only searching for file with *.bak and *.tm extension! I tried generate backup file with .bak extension and tried restore into SQl server 2005 express edition but still it is not allowing to do so! I also tried copy my database's data file and log file and paste it under SQL server 2005 express edition Data folder and still not able to read the tables.Is that any ways to do restoring for this SQL server 2000 backup file into SQL server 2005 express edition! Anybody can help me on this please...:eek:
I am having a hard time finding the executable file to start sql express 2005 or SQL exress 2005 with advance services. I installed the SQL express and had the desktop icon....but I thought i would need to uninstall it before installing SQL 2005 with advance services. Now I can not find anything to start the program.
Hello Everyone, I am trying to restore a bak file which came with code for a tutorial. I think it is safe to restore, but sql server 2005 express has the following problem when I try to restore it. TITLE: Microsoft SQL Server Management Studio Express------------------------------ Restore failed for Server 'BOBSQLEXPRESS'. (Microsoft.SqlServer.Express.Smo) For help, click: http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&ProdVer=9.00.3042.00&EvtSrc=Microsoft.SqlServer.Management.Smo.ExceptionTemplates.FailedOperationExceptionText&EvtID=Restore+Server&LinkId=20476 ------------------------------ADDITIONAL INFORMATION: System.Data.SqlClient.SqlError: The operating system returned the error '5(Access is denied.)' while attempting 'RestoreContainer::ValidateTargetForCreation' on 'C:Program Files (x86)Microsoft SQL ServerMSSQL.1MSSQLDashboard.mdf'. (Microsoft.SqlServer.Express.Smo) For help, click: http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&ProdVer=9.00.3042.00&LinkId=20476 The links given for help have no information about the problem and I'm not really sure where I should be looking to solve this. I'm a newbie to databases so if you could provide a step-by-step answer that would be best. Thanks in advance. Robert
Hi All, I have a .sql file with all my queries written in it. Now I want to know, Is it possible to run this sql file in SQL Server 2005 Express Edition like we can do in Oracle? If it is possible then tell me how to do it?Thanx in advance for any kind of help.Regards,Paramhans Dubey.
I'm a little stuck here. How can I import a flat tab delimited file into a SQL 2005 Express table? The standard DTS and import features are not there :-(Thanks,Casey
I am just starting to learn SQL 2005 Express. After opening the Management Studio Express, I right Click on the Databases node and create new database. then create a name etc. The problem is that when I click ok to create the new database, I get a warning saying that Input a filename. However when I click on filename (after filepath) it is greyed out and I cant add a filename.
I have database written in SQL SERVER 2005 since last two year .Now the Database size become 33MB, and the log file become 450 MB . The log file is too large for me . Do you any know how clear the log file in SQL SERVER 2005 EXPRESS SP2 ?.Thanks
Hi All,I wrote a vbscript file which copies one table records to another database table. I wrote error handling to send an email if error occurs when copying records from one table to another. I want to schedule a sql job and give this file to execute. Could anyone plz tell me how to schedule sql job which runs vbscript file. i selected ActiveXScript and choose vbscript and gave path. I'm not understanding what the command should be given to run vbscript file. The result of giving path is job is failing.Any help would be appreciated...plzzzzzzzthankscarol
I am trying to import some data from a csv file on a regular basis. This file, however, is stored on a website. I can't seem to find a way, either using DTS or a stored procedure to make this task simple. If the file is at http://www.mysite.com/import.csv is there anyway I can get DTS to download that file and import it into a new table?
Hi Guys, how many connections does sql 2005 express allow to .mdf file. I stumpled on info on a microsoft site (actually a forum post on msdn) that sql server express allows only a single connection to an .mdf file. Iam intrested in this because i developed reporting services reports in BIS and iam having problems. If i run a report from report manager, i have to wait for close to 20 minutes before i can be able to run my asp.net application agian. Else if i insert data or retrieve data from my asp.net application, then i have to wait again for 20 minutes or more before i can be able to run my reports else i will get an error that a connection can not be made to the database or that the database is being used by another process. So in all cases, i have to wait for 20--30 minutes before a connection can be made to the .mdf file. i.e after running a report or after inserting or retrieving data from the database through my asp.net application. Iam using sql sever 2005 express with advanced services and visual web developer on windows server 2003. Any ideas or help.
All -- Please help. Is it possible to connect to MDF file without having SQL Server 2005 Express installed on the machine? That is-- can one connect directly to an MDF in the same way and Access MDB file can be used? If no, then is there any way around this? If yes, then are there any limitations? Please advise. Thank you. -- Mark Kamoski