![]() |
|
Identify and resolve SQL Server problems before they happen

|
|
By: Edwin Sarmiento | Read Comments (39) | Related Tips: More > Express Edition |
As a lot of line-of-business applications are being built with SQL Server 2005 Express Edition as their backend database, we need to make sure that we backup the system and the user databases running on these instances. Unfortunately, SQL Server 2005 Express Edition does not come with SQL Agent which we would normally use to create a database maintenance plan to backup all the databases. How do we perform a backup of our system and user databases in SQL Server 2005 Express Edition similar to how we do it in other editions?
We can use a combination of VBScript and TSQL with Task Manager in Windows to automate the creation of user and system database backups in SQL Server 2005 Express Edition.
Note: All files should be saved in folder E:\SQL_Backup\scripts. This can be changed, but this example is setup for this folder. If you save to a different folder you will need to update the scripts accordingly.
Step 1 - Create the TSQL script
The TSQL script below generates a database backup similar to the formatting generated by the database maintenance plan, taking into account the date and time the backup files were generated. We save the script as a .sql file, E:\SQL_Backup\scripts\backupDB.sql, which we will call from a batch file using sqlcmd.
DECLARE @dateString CHAR(12), @dayStr CHAR(2), @monthStr CHAR(2), @hourStr CHAR(2), @minStr CHAR(2)
--month variable
IF (SELECT LEN(CAST(MONTH(GETDATE()) AS CHAR(2))))=2
SET @monthSTR=CAST(MONTH(GETDATE()) AS CHAR(2))
ELSE
SET @monthSTR= '0' + CAST(MONTH(GETDATE()) AS CHAR(2))
--day variable
IF (SELECT LEN(CAST(DAY(GETDATE()) AS CHAR(2))))=2
SET @daySTR=CAST(DAY(GETDATE()) AS CHAR(2))
ELSE
SET @daySTR='0' + CAST(DAY(GETDATE()) AS CHAR(2))
--hour variable
IF (SELECT LEN(DATEPART(hh, GETDATE())))=2
SET @hourStr=CAST(DATEPART(hh, GETDATE()) AS CHAR(2))
ELSE
SET @hourStr= '0' + CAST(DATEPART(hh, GETDATE()) AS CHAR(2))
--minute variable
IF (SELECT LEN(DATEPART(mi, GETDATE())))=2
SET @minStr=CAST(DATEPART(mi, GETDATE()) AS CHAR(2))
ELSE
SET @minStr= '0' + CAST(DATEPART(mi, GETDATE()) AS CHAR(2))
--name variable based on time stamp
SET @dateString=CAST(YEAR(GETDATE()) AS CHAR(4)) + @monthStr + @dayStr + @hourStr + @minStr
--=================================================================
DECLARE @IDENT INT, @sql VARCHAR(1000), @DBNAME VARCHAR(200)
SELECT @IDENT=MIN(database_id) FROM SYS.DATABASES WHERE [database_id] > 0 AND NAME NOT IN ('TEMPDB')
WHILE @IDENT IS NOT NULL
BEGIN
SELECT @DBNAME = NAME FROM SYS.DATABASES WHERE database_id = @IDENT
/*Change disk location here as required*/
SELECT @SQL = 'BACKUP DATABASE '+@DBNAME+' TO DISK = ''E:\SQL_Backup\'+@DBNAME+'_db_' + @dateString +'.BAK'' WITH INIT'
EXEC (@SQL)
SELECT @IDENT=MIN(database_id) FROM SYS.DATABASES WHERE [database_id] > 0 AND database_id>@IDENT AND NAME NOT IN ('TEMPDB')
END
Step 2 - Create the VBScript file
Next, we will need to create a VBScript file which will be responsible for cleaning up old copies of the database backups. The script also writes to a log file which records the database backup files.
On Error Resume Next
Dim fso, folder, files, sFolder, sFolderTarget
Set fso = CreateObject("Scripting.FileSystemObject")
'location of the database backup files
sFolder = "E:\SQL_Backup\"
Set folder = fso.GetFolder(sFolder)
Set files = folder.Files
'used for writing to textfile - generate report on database backups deleted
Const ForAppending = 8
'you need to create a folder named “scripts” for ease of file management &
'a file inside it named “LOG.txt” for delete activity logging
Set objFile = fso.OpenTextFile(sFolder & "\scripts\LOG.txt", ForAppending)
objFile.Write "================================================================" & VBCRLF & VBCRLF
objFile.Write " DATABASE BACKUP FILE REPORT " & VBCRLF
objFile.Write " DATE: " & FormatDateTime(Now(),1) & "" & VBCRLF
objFile.Write " TIME: " & FormatDateTime(Now(),3) & "" & VBCRLF & VBCRLF
objFile.Write "================================================================" & VBCRLF
'iterate thru each of the files in the database backup folder
For Each itemFiles In files
'retrieve complete path of file for the DeleteFile method and to extract
'file extension using the GetExtensionName method
a=sFolder & itemFiles.Name
'retrieve file extension
b = fso.GetExtensionName(a)
'check if the file extension is BAK
If uCase(b)="BAK" Then
'check if the database backups are older than 3 days
If DateDiff("d",itemFiles.DateCreated,Now()) >= 3 Then
'Delete any old BACKUP files to cleanup folder
fso.DeleteFile a
objFile.WriteLine "BACKUP FILE DELETED: " & a
End If
End If
Next
objFile.WriteLine "================================================================" & VBCRLF & VBCRLF
objFile.Close
Set objFile = Nothing
Set fso = Nothing
Set folder = Nothing
Set files = Nothing
Step 3 - Create the batch file that will call the TSQL script and the VBScript file
We need to create the batch file which will call both the TSQL script and the VBScript file. The contents of the batch file will be a simple call to the sqlcmd.exe and a call to the VBScript file using either wscript.exe or simply calling the file. Save the file as E:\SQL_Backup\scripts\databaseBackup.cmd and save it in the scripts subfolder
REM Run database backup cleanup script
E:\SQL_Backup\scripts\deleteBAK.vbs
Step 4 - Create a task in Windows Task Scheduler
Create a daily task in Windows Task Scheduler that will call the batch file created in the previous step. This can be found in the Control Panel -> Scheduled Tasks or under Start -> All Programs -> Accessories -> System Tools -> Scheduled Tasks.
Since we are using Windows authentication to run the TSQL script, use a Windows account that is a member of the db_backupoperator role of all the databases




| Wednesday, April 30, 2008 - 5:09:09 PM - MrSato | Read The Tip |
|
For those of us who don't know scripting languages, can you specify what needs to be edited to reflect each database we want to backup, and anything else that might need editing? The only obvious one, which is notated in the script, is where to put the log file. Thanks a bunch for the how-to though! Looks like a slam dunk once I know where to put the database name(s). |
|
| Friday, May 09, 2008 - 1:30:45 AM - bass_player | Read The Tip |
|
The line containing the script SELECT @IDENT=MIN(database_id) FROM SYS.DATABASES WHERE [database_id] > 0 AND NAME NOT IN ('TEMPDB') tells us which database not to include. In this case, all databases will be backed up except for TEMPDB. To include a list of databases, simply remove the NOT in the script and specify your databases inside the parenthesis like this SELECT @IDENT=MIN(database_id) FROM SYS.DATABASES WHERE [database_id] > 0 AND NAME IN ('database1', 'database2', 'etc') AND NAME NOT IN ('TEMPDB') You would still need to exclude the TEMPDB database as you cannot run a backup command for that. Since I wanted every database to be backed up, it would be easier to just exclude the TEMPDB instead I would strongly recommend learning TSQL scripting as this is essential to manage SQL Server well |
|
| Wednesday, May 14, 2008 - 4:18:03 PM - cainboot | Read The Tip |
|
I am getting an error when I run the sqlcmd file. The error is "Msg102, Level 15, State 1 - Incorrect syntax near 'S' - When I remove the sqlcmd from databaseBackup.cmd and run it independently, it works. Any ideas?
Thank you very much! |
|
| Friday, May 16, 2008 - 8:42:44 AM - bass_player | Read The Tip |
|
There should be a space between the instance name and the -E switch. Check out the documentation for sqlcmd on MSDN. Here's a sample sqlcmd call for a server instance named TESTSERVER\TEST sqlcmd -STESTSERVER\TEST -E -i"E:\SQL_Backup\scripts\backupDB.sql" |
|
| Tuesday, May 20, 2008 - 7:21:40 AM - simondoubt | Read The Tip |
|
Thanks very much for these scripts. I'm using SQL Server 2005 Standard Edition with the Maintenance Plan, but have adapted the VB script to delete the old BAK and TRN files once they've been moved onto tape. Thanks again! |
|
| Tuesday, May 20, 2008 - 9:15:46 AM - bass_player | Read The Tip |
|
It's great to hear that the tip is of great help. Your feedback is very much appreciated. It would also be great if you could highlight some issues you want solved and we would be be happy to provide tips to resolve them |
|
| Wednesday, May 21, 2008 - 6:53:39 AM - simondoubt | Read The Tip |
|
Okay - here goes, the next step in implementing this great little VB script. I would like to embed the VB script as part of an SQL Server agent job, which I could then include as part of my maintenance plan. So, I tried to create a new job with one step: an Operating System (CmdExec) step. I clicked on OPEN on the Job Step Properties page, browsed to the location of the vbs file then selected it, and the code was automatically inserted into the main window of the Job Step Properties page, as such:
I didn't change any other settings, Here's the error I got:
Any info or feedback you may have would be terrific - thank you very much. Best, Simon |
|
| Monday, May 26, 2008 - 4:03:30 AM - bass_player | Read The Tip |
|
Use an ActiveX Script type and select VBScript in the option instead of Operating System (CmdExec) |
|
| Monday, May 26, 2008 - 6:33:13 AM - simondoubt | Read The Tip |
|
Great - that worked perfectly, thank you so much. In case anyone out there is playing along at home, I also modified one of the conditions to check for TRN files (transactionl log files) as well as BAK file to delete. 'Check if the file extension is BAK or TRN Thanks again, this tutorial and all the help have been terrific - much appreciated. - Simon |
|
| Wednesday, May 28, 2008 - 12:47:32 PM - simondoubt | Read The Tip |
|
Hello, All: Would there be any way to have the script look through nested directories to delete backup files in them as well? In other words, instead of just deleting files in the root of the sFolder variable, I'd like the script to search through sub-directories in sFolder as well. As always, thanks in advance for any input/suggestions. -Simon |
|
| Thursday, May 29, 2008 - 5:59:56 PM - bass_player | Read The Tip |
|
Try out this script and customize according to your need.
Sub getCount() Sub CheckFolder(strPath) 'check if the file extension is BAK
|
|
| Thursday, August 14, 2008 - 8:18:19 AM - LauraV | Read The Tip |
|
Can you help one more person? These scripts work terrific. I have only had an issue on one instance that has Sharepoint databases with lots of dashes in the database name. It backs up all the databases without dashes perfectly, but throws an error on the others: Msg 102, Level 15, State 1, Server MSOCSP02\OFFICESERVERS, Line 1 I tried putting in a semicolon after your SELECT @SQL = 'BACKUP DATABASE '+ @DBNAME +' TO DISK = ''D:\SQLBack\'+@DBNAME+'_db_' + @dateString +'.BAK'' WITH INIT'; line. This is not working though. Thanks in advance for your help! |
|
| Thursday, August 14, 2008 - 10:31:31 AM - aprato | Read The Tip |
|
Laura, trying putting brackets around the @dbname variable |
|
| Tuesday, August 19, 2008 - 3:01:09 AM - bass_player | Read The Tip |
|
Something like this SELECT @SQL = 'BACKUP DATABASE ['+@DBNAME+'] TO DISK = ''E:\SQL_Backup\'+@DBNAME+'_db_' + @dateString +'.BAK'' WITH INIT'
|
|
| Tuesday, August 19, 2008 - 10:19:21 AM - LauraV | Read The Tip |
|
Thanks so much ya'll / youse, depending on what region you are from. That worked perfectly! Appreciate your time in responding, thanks a million. |
|
| Wednesday, August 20, 2008 - 10:14:38 PM - bass_player | Read The Tip |
|
Great to hear it worked. Feel free to post questions on the forum for anything related to SQL Server |
|
| Thursday, October 23, 2008 - 5:47:44 AM - mavina | Read The Tip |
|
This is good but would be very good if it wrote to the event log in the event of a failure, automatic monitoring would then alert admins to the problem. Have been trying to achieve this with little success. |
|
| Monday, October 27, 2008 - 9:32:43 PM - bass_player | Read The Tip |
|
I have a script that logs to a text file and a script that reads the text file for errors. It then sends an email notification should the job fails. I have one for VBScript and one for PowerShell. I'll work on an article for that if you provide me with the specifics of what you wanted done :-) |
|
| Wednesday, October 29, 2008 - 7:27:05 AM - mavina | Read The Tip |
|
I have created a stored procedure (see below) and use following to call it: sqlcmd -E -o d:\test\SQLBK_backup.txt -q "EXIT (exec mydb.dbo.mybackup @drive='D',@inst='DEFAULT')" I want to be able to use EVENTCREATE to generate an error if any of the backups fail, I the tried to use EXEC @RC= but this does not seem compatible with the EXEC (@SQL) so I assume I am missing the point somewhere! ALTER PROCEDURE [dbo].[mybackup] AS WHILE @ident IS NOT NULL /* full backup of all databases */ WHILE @ident IS NOT NULL
|
|
| Thursday, November 06, 2008 - 2:34:34 AM - janodega | Read The Tip |
|
Thank you for the tip, it works great! Do you have tip on doing restore of the backup files as well..? Best Regards, janodega |
|
| Saturday, November 15, 2008 - 12:58:26 AM - bass_player | Read The Tip |
|
This tip has been posted sometime this week. Check it out if it meets your requirements |
|
| Monday, May 11, 2009 - 5:40:25 AM - berndn | Read The Tip |
|
Thanks for the great script ! Is it possible to include a "RESTORE verifyonly" to this job ? I'm stuck ;) |
|
| Monday, May 11, 2009 - 6:18:38 AM - admin | Read The Tip |
|
In this section of the T-SQL code: BEGIN
BEGIN SELECT @IDENT=MIN(database_id) FROM SYS.DATABASES WHERE [database_id] > 0 AND database_id>@IDENT AND NAME NOT IN ('TEMPDB') |
|
| Monday, May 11, 2009 - 6:46:14 AM - berndn | Read The Tip |
|
Thanks a lot. This makes sense. |
|
| Monday, May 18, 2009 - 3:08:38 AM - stefaan | Read The Tip |
|
It works fine, but how to restore from these backups? (Are the ldf files included in the backup?)
|
|
| Friday, June 05, 2009 - 12:15:27 PM - bass_player | Read The Tip |
|
The backup files include the database files (MDF, LDF, NDF, etc.) Although this article is for SQL Server Express, it works with just about any edition. So your restore process would include a RESTORE DATABASE command or Management Studio |
|
| Friday, June 19, 2009 - 1:30:58 PM - work4rus | Read The Tip |
|
Gentelmen, you are wasting your time. Why spend it on such a trivial task as DB backup - it could be achieved way better by off the shelf product like SQLBackupAndFTP. If it is just for fun - fine - as much as you want! But if you get paid for it - you are not effective and wasting money. |
|
| Monday, August 30, 2010 - 11:03:29 AM - gil | Read The Tip |
|
thanks! works perfectly! |
|
| Monday, November 19, 2012 - 7:57:47 AM - jan | Read The Tip |
|
just needed customization on local setting and works great.. |
|
| Thursday, January 17, 2013 - 9:49:52 AM - Mark R. | Read The Tip |
|
Another option is to try SQL Backup Master, a free tool for creating SQL Server backups. http://www.sqlbackupmaster.com/ |
|
| Friday, February 08, 2013 - 9:32:20 AM - Wesley Meijer | Read The Tip |
|
Nice article, Used it on different occations and works really well. I fancy the 'prefer the 'RESTORE VERIFYONLY FROM DISK' version. This way your backups are 100% reliable.
Thanks for the article.
|
|
| Friday, February 08, 2013 - 10:41:16 AM - bass_player | Read The Tip |
|
Hi Wesley, I'm with you on using the RESTORE VERIFYONLY FROM DISK as a way to validate. However, I'm a bit paranoid when it comes to backups: the only way for me to trust them is when I have successfully tested the restore :-) |
|
| Monday, February 11, 2013 - 5:36:44 AM - Wesley | Read The Tip |
|
Its always a good thing to restore your backups on a preffered scheduled basis. So you have an emergency plan and know what to do in an emergency situation. If you are uncertain or paranoid you could restore your backups in a different instance so you can test your data or use it on a test enviroment. Beats waiting for an emergeny to accure. Good luck |
|
| Tuesday, February 26, 2013 - 2:22:25 AM - Gobinda | Read The Tip |
|
REM Run TSQL Script to backup databases
REM "Below is the modified sqlcmd string to backup databases"
sqlcmd -S INSTANCENAME -i"D:\Program Files\MSSQL.1\MSSQL\Backup\backup.sql"
|
|
| Tuesday, May 07, 2013 - 10:13:29 AM - Andy Hetherington | Read The Tip |
|
Hi there,
I stumbled across your script as we have an SQL Express version hosting a Sharepoint setup and I wanted a backup of the DB's. However upon running the sql script i get an error as shown below
Processed 360 pages for database 'master', file 'master' on file 1. Processed 2 pages for database 'master', file 'mastlog' on file 1. BACKUP DATABASE successfully processed 362 pages in 0.364 seconds (8.146 MB/sec). Processed 152 pages for database 'model', file 'modeldev' on file 1. Processed 3 pages for database 'model', file 'modellog' on file 1. BACKUP DATABASE successfully processed 155 pages in 0.438 seconds (2.889 MB/sec). Processed 6632 pages for database 'msdb', file 'MSDBData' on file 1. Processed 6 pages for database 'msdb', file 'MSDBLog' on file 1. BACKUP DATABASE successfully processed 6638 pages in 3.591 seconds (15.141 MB/sec). Msg 102, Level 15, State 1, Line 1 Incorrect syntax near '-'. Msg 319, Level 15, State 1, Line 1 Incorrect syntax near the keyword 'with'. If this statement is a common table expression or an xmlnamespaces clause, the previous statement must be terminated with a semicolon. Msg 102, Level 15, State 1, Line 1 Incorrect syntax near '-'. Msg 319, Level 15, State 1, Line 1 Incorrect syntax near the keyword 'with'. If this statement is a common table expression or an xmlnamespaces clause, the previous statement must be terminated with a semicolon. Processed 1128 pages for database 'WSS_Search_TGNET5', file 'WSS_Search_TGNET5' on file 1. Processed 1 pages for database 'WSS_Search_TGNET5', file 'WSS_Search_TGNET5_log' on file 1. BACKUP DATABASE successfully processed 1129 pages in 0.885 seconds (10.450 MB/sec). Processed 1928 pages for database 'WSS_Content', file 'WSS_Content' on file 1. Processed 2 pages for database 'WSS_Content', file 'WSS_Content_log' on file 1. BACKUP DATABASE successfully processed 1930 pages in 1.461 seconds (10.820 MB/sec). Processed 1344 pages for database 'WSS_Content_4d1d522f951d4ac3b4326c3fb30285a6', file 'WSS_Content_4d1d522f951d4ac3b4326c3fb30285a6' on file 1. Processed 2 pages for database 'WSS_Content_4d1d522f951d4ac3b4326c3fb30285a6', file 'WSS_Content_4d1d522f951d4ac3b4326c3fb30285a6_log' on file 1. BACKUP DATABASE successfully processed 1346 pages in 0.917 seconds (12.019 MB/sec). Processed 1344 pages for database 'WSS_Content_43b1b6fa6d0646eabffbc6950df4995c', file 'WSS_Content_43b1b6fa6d0646eabffbc6950df4995c' on file 1. Processed 2 pages for database 'WSS_Content_43b1b6fa6d0646eabffbc6950df4995c', file 'WSS_Content_43b1b6fa6d0646eabffbc6950df4995c_log' on file 1. BACKUP DATABASE successfully processed 1346 pages in 0.952 seconds (11.580 MB/sec). Msg 102, Level 15, State 1, Line 1 Incorrect syntax near '-'. Msg 319, Level 15, State 1, Line 1 Incorrect syntax near the keyword 'with'. If this statement is a common table expression or an xmlnamespaces clause, the previous statement must be terminated with a semicolon. Msg 102, Level 15, State 1, Line 1 Incorrect syntax near '-'. Msg 319, Level 15, State 1, Line 1 Incorrect syntax near the keyword 'with'. If this statement is a common table expression or an xmlnamespaces clause, the previous statement must be terminated with a semicolon. Processed 13048 pages for database 'WSS_Search_TGNET5_57a1b1d0040f437587dc951113cbf707', file 'WSS_Search_TGNET5_57a1b1d0040f437587dc951113cbf707' on file 1. Processed 8 pages for database 'WSS_Search_TGNET5_57a1b1d0040f437587dc951113cbf707', file 'WSS_Search_TGNET5_57a1b1d0040f437587dc951113cbf707_log' on file 1. BACKUP DATABASE successfully processed 13056 pages in 7.704 seconds (13.882 MB/sec). Processed 43152 pages for database 'WSS_Content_c150bdefc0134f209ae7c123c7c55f10', file 'WSS_Content_c150bdefc0134f209ae7c123c7c55f10' on file 1. Processed 2 pages for database 'WSS_Content_c150bdefc0134f209ae7c123c7c55f10', file 'WSS_Content_c150bdefc0134f209ae7c123c7c55f10_log' on file 1. BACKUP DATABASE successfully processed 43154 pages in 25.643 seconds (13.786 MB/sec). I am not a SQL guru by any means so any help gratefully recieved on how to overcome this error as not all the DB's are being backed up.
Thanks Andy |
|
| Tuesday, May 07, 2013 - 1:02:52 PM - Greg Robidoux | Read The Tip |
|
@Andy Hetherington You probalby need to be [ ] around the @DBNAME like the following: SELECT @SQL = 'BACKUP DATABASE ['+@DBNAME+'] TO DISK = ''E:\SQL_Backup\'+@DBNAME+'_db_' + @dateString +'.BAK'' WITH INIT'
|
|
| Tuesday, May 07, 2013 - 1:28:38 PM - bass_player | Read The Tip |
|
Greg is correct. Since the names of the SharePoint databases have funky GUID values with minus signs in them, you need to enclose the database names around the square brackets |
|
| Wednesday, May 08, 2013 - 4:19:20 AM - Andy Hetherington | Read The Tip |
|
@Greg & bass_player - thanks very much that did the trick :) |
|
| Thursday, May 09, 2013 - 10:20:18 AM - Andy Hetherington | Read The Tip |
|
Hi All,
Sorry I have another query - I am successfully backing up our Sharepoint DB's using the above tweak. I have now attempted to backup a Database under different instance but on the same SQL server that hosted the sharepoint yet I get a Named Piped Provider: Could not open a connection to SQL Server [53] error when running the Sqlcmd Any idea what could be causing this error? Thanks Andy |
|
|
privacy | disclaimer | copyright | advertise | about authors | contribute | feedback | giveaways | user groups Some names and products listed are the registered trademarks of their respective owners. Edgewood Solutions LLC | MSSharePointTips.com | MSSQLTips.com |