Web design and hosting, database, cloud and social media solutions that deliver business results
  • Business Solutions
    • Robotic Process Automation
    • Bespoke Software
    • Database Services
      • Data Integration
      • Datawarehouse Services
      • Power BI
      • Server Upgrade and DBA Services
    • Web Services
      • Logo Design
      • Payment Gateways
      • Web Localisation and Translation
      • Web Site Optimisation
      • Web Site Security
      • Technical Tools
    • Cloud Services
      • Amazon Web Services
      • Google Cloud Services
      • Microsoft Azure
    • Microsoft 365
      • Enabling the Multi Factor Authentication Application
      • Office 365 DNS Settings Generator
    • IT Hardware
    • Social Media Services
  • Academy
    • Our Test Environment
    • Learning Databases
      • The Basics
      • Get Open Query
      • SQL Server Data
      • SQL Server Maintenance
      • Using SQL Server Dates
      • Using SQL Server Functions
      • Using SQL Server Pivot-Unpivot
      • Technical Tools
    • Learning Web Design
      • Building Ousia Content Management System
      • Using ASP-NET
      • Using CSS
      • Using JavaScript
    • Learning Cloud and IT Services
      • Task Scheduler Error 2147943645
      • Blocking Blank Senders
      • Requesting SSL and Generation of PFX file in OpenSSL Simple Steps
    • Using Social Media
      • Asking for a Google Review
      • Changing a Facebook account from personal to business
      • Choosing where to focus Social Media effort
      • Social Media Image Sizes
      • Using Meta Data to set Social Media Images
  • About
    • Blog
      • Building an entry level gaming machine
      • Google Core Update Jan 2020
      • Hot Chilli Internet Closure
      • How To Choose Content For Your Website Adverts Leaflets
      • Preventing Online Scam
      • Skimmers of the gig economy
      • The most annoying things about websites on the Internet
      • Top 5 websites for free Vector Graphics
    • Careers
      • Translator English-Japanese
      • Translator English-Portuguese
      • Translator English-Spanish
      • Translator English-Turkish
    • Portfolio
    • Regulatory
    • Team
      • Chester Copperpot
      • Gavin Clayton
      • Sai Gangu
      • Suneel Kumar
      • Surya Mukkamala
عربى (AR)čeština (CS)Deutsch (DE)English (EN-GB)English (EN-US)Español (ES)فارسی (FA)Français (FR)हिंदी (HI)italiano (IT)日本語 (JA)polski (PL)Português (PT)русский (RU)Türk (TR)中国的 (ZH)

A complete maintenance plan for SQL Server 2008

SQL Server Maintenance Plan that can backup and restore database files on multiple servers, re-organise or rebuild indexes dependent on time

Optimising Databases

Database Maintenance Plan

This section is dedicated to keeping databases optimised. In this example, we are going to set up the code to do the following (see a rough diagram of how the servers are connected);

  • Backup database from live server to a shared backup folder
  • Re-Index Database
  • Kill all connections and restore the database on reporting server.
  • Linked Servers will be in a separate article soon
  • Log Shipping will be in a separate article soon

When doing it cross server, you will need to allow the account that SQL Server is running from access to the target servers file system.

All SQL code is run from a utilities database, and schema set to "maint"

There are a host of other articles we have written below that may be of interest to you.

Complete Maintenance Plan

Now we can manage all of these separate code segments with another procedure that will call them in the correct order, this will be put in the live server. The code runs as follows;

  • Work out the time           
  • If it is evening re-index the database           
  • Run a backup of the database (add where you need)           
  • If it is evening back up the other databases (add where you need)           
  • Kill connections and restore database (add where you need)       

This code has been tried and tested and ran for periods of months without any issues.

Please note that the shrinking of log files and database files should be kept to a minimum, by running a backup you are emptying the log (although it will retain the space used). If it is needed when it should be run outside of normal working hours.

SQL Code

Use [utilities]GOCREATE PROC [maint].MaintenancePlan AS BEGINDECLARE @BackupType VARCHAR(1)='E'IF DATEPART(HOUR,GETDATE()) BETWEEN 5 AND 21 BEGINSET @BackupType='D'END--EXEC ('USE TempDb; DBCC SHRINKFILE(templog, 0)');--This is only needed when space is at a premium!--Re-index LiveIF @BackupType='E' EXEC [maint].DatabaseReIndex 'dbname'--Create BackupBACKUP DATABASE TO DISK=N'{backuplocation}{dbname}.bak'WITH NOFORMAT, INIT, NAME =N'{dbname}', SKIP, NOREWIND, NOUNLOAD, STATS= 10;--EXEC ('USE ; DBCC SHRINKFILE(_log, 0)');--This is only needed when space is at a premium!--Backup Other Files at NightIF @BackupType='E' BEGIN  EXEC [maint].DatabaseReIndex 'dbname'  --Backup Others  BACKUP DATABASE [databasename] TO DISK=N'{backuplocation}{dbname2}.bak'  WITH FORMAT,INIT, NAME =N'{dbname2}',SKIP, NOREWIND, NOUNLOAD,  STATS= 10END--Restore Backups on other serverEXEC [server].[utilities].[maint].KillConnections 'dbname';EXEC [server].[utilities].[maint].RestoreDatabase_{dbname};--Restore Backups on other server for db_2 etcIF @BackupType='E' BEGIN  EXEC [server].[utilities].[maint].KillConnections 'dbname2';  EXEC [server].[utilities].[maint].RestoreDatabase_{dbname2};ENDENDGO

Backup Database

backup database screenshot

To get the code to backup your database, it is easiest to script the code from SSMS.

Follow the process you would normally use, and then select "Script Action to New Query Window".

Copy this code into the maintenance plan.

Re-Index Database

Next we can add some code to re-index our database, this again is a share stored procedure where you only need to tell the system the name.

To avoid code duplication, you can get read about it on the link below.

More: Stored Procedure to rebuild or reorganise fragmented database indexes

Kill Connections

When performing a restore on the database, you can only have one connection to it (the process performing the restore), therefore we can create a stored procedure to close all connections apart from the current process. We have again created a separate article for this.

More: Stored Procedure to kill all connections to selected database

Restore Database

This code can also be scripted from SQL Server Management Studio. If you add this code to a stored procedure, you can call it from other processes and even other servers really easily. We've moved this into a separate article to cover more options.

More: Restore Database from Stored Procedure

7Zip Database Backup

SQL Code to enable xp_cmdshell and then run a database backup backup through the 7Zip command line.

Auditing and synchronising data in tables cross database

Auditing and synchronising tables in different databases, with different data structure using a trigger

Remove a user without leaving orphan data

Completely remove users from SQL Server without leaving orphan data

Context trigger for data auditing

SQL Server 2008, Easy data auditing - Using a trigger and context to trace updates to an SQL Table

Disk space and database size alerts

Create a stored procedure that will send out disk space and database alerts via email that you can attach to a job

Kill all connections to selected database

SQL Stored Procedure to kill all connections to selected database or server except for the process calling it.

Rebuild or reorganise fragmented indexes

A re-useable Stored Procedure that you can call to re-index any database by entering the name of the database.

Restore Database from Stored Procedure

Create a centralised, generic and re-useable stored procedure using dynamic SQL script that can restore databases using a number of parameters as part of a wider maintenance plan

Searching for text in stored procedures and functions

SQL Server search for text in stored procedures and functions and get the line numbers of each row

Author

Was this helpful?

Please note, this commenting system is still in final testing.
Copyright Claytabase Ltd 2020

Registered in England and Wales 08985867

Site Links

RSSLoginLink Cookie PolicySitemap

Social Media

facebook.com/Claytabaseinstagram.com/claytabase/twitter.com/Claytabaselinkedin.com/company/claytabase-ltd

Get in Touch

+442392064871info@claytabase.co.ukClaytabase Ltd, Unit 3d, Rink Road Industrial Estate, PO33 2LT, United Kingdom

Partnered With

The settings on this site are set to allow all cookies. These can be changed on our Cookie Policy & Settings page.
By continuing to use this site you agree to the use of cookies.
Ousia Logo
Logout
Ousia CMS Loader