Saturday, August 17, 2013

Create Automated Maintenance Jobs with SQL Server Maintenance Plan

SQL Server maintenance plan is a very useful and simple way to create automated maintenance plans to optimise and backup your database regularly. You can perform database maintenance and optimised your database by creating simple workflow of tasks with graphical user interface in SSMS. We are going to create a maintenance plan for full database backup and we will set the schedule in design window. So if you are database administrator or developer who wants to maintain and optimise database in quick way then here is a tool for you.
MaintenancePlan
To create maintenance plan go to Object Explorer –> Management –> Maintenance Plans –> right click and select New Maintenance Plan…
01_NewPlan
It will prompt to provide maintenance plan name, put the name and click OK. Design window will be open and on left side you will get Toolbox. If by default toolbox is not available, you can select the same by pressing Ctrl+Alt+X or select from View menu.
02_DesignWindow
Toolbox provides different useful maintenance plan tasks as given below:
– Backup Database Task
– Check Database Integrity Task
– Execute SQL Server Agent Job Task
– Execute T-SQL Statement Task
– History Cleanup Task
– Maintenance Cleanup Task
– Notify Operator Task
– Rebuild Index Task
– Reorganise Index Task
– Shrink Database Task
– Update Statistics Task
Now here we have to create Backup Database Task so drag and drop the task to design window from toolbox. Now right click on Backup Database Task and select Edit… It will open Backup Database Task where you have to provide necessary details. Select your database connection, backup type and name of database to backup then select the database backup path from Folderoption. Select the Folder path and click OK.
03_Backup DatabaseTask Window
On backup database task window you also have options like copy-only backup and you can also specify backup set expiry date. Then you can choose to backup database to either disk or tape as per your requirements. You can also divide the database backup into one or more files. You can choose verify backup integrity and set backup compression option if you want to save the disk space. Now click OK button and you will be back to design window. Now select Schedule option from design window and set the required schedule and click OK.
04_SetSchedule
Now click on Save button from SQL Server Management Studio, which will create automated job and plan for your task. Once it is saved you can verify the job in jobs node and also plan is created under maintenance plans. So this is very simple and effective way to create a maintenance plans for your database servers.

SQL Server Recovery Models Overview – Simple, Full, Bulk-logged

Recovery model plays very important role when it comes to data recovery or to minimise data loss. You need excellent understanding of your business requirements and importance of data. Depending on scenarios you have to decide whether you have to select simple, full or bulk-logged recovery model. Recovery model plays important role to decide recovery strategy. For example, in banking operations you can’t take risk to lose any transaction and each record is very important.
RecoveryModel
In SQL Server, there are three types of recovery models.
1. Simple Recovery Model
2. Full Recovery Model
3. Bulk-logged Recovery Model
How to check which recovery model is set for your database.
SELECT name "Database Name", recovery_model_desc
FROM sys.databases
GO

1. Simple Recovery Model

In simple recovery  model, you will not be able to do log backups as it automatically truncates log. So it minimizes admin works and saves log space. But there are some risks also, if database is damaged or data has lost then you won’t be able to recover it if you don’t have backups. You can recover only the point where you have already taken backup. Simple recovery model truncates log after checkpoint, when checkpoint occurs SQL Server truncates log before the VLF which contains the Min. LSN value.
You will not be able to perform following operations in simple recovery model.
– Log Shipping
– Database Mirroring
–  AlwaysOn feature
– Point-in-Time restores or data recovery etc.
You can use simple recovery model when:
– Data is not so important and you do not need point in time recovery.
– You can take risk to lose some data because your business requirement is different.
– You can manage if database is corrupted or damaged and you are comfortable losing data during the point between last backup and current failure point.
– You don’t want to backup and restore transaction log and you can manage with full backup and differential backup.
How to set Simple Recovery Model
USE master
GO
ALTER DATABASE Inventory SET RECOVERY SIMPLE
GO

2. Full Recovery Model

Full recovery model is by default set when you install SQL Server. If you will create new databasethen recovery model will be set according to model database. In full recovery model alltransaction logs are retained till the time of backup. In this recovery model you can recover thedatabase till the point of failure if tail of the log is backed up.
You can use full recovery model when:
– You need point-in-time data recovery.
– Data is very important and you cannot lose any data.
– You want to use advanced features like log shipping, mirroring, AlwaysOn etc.
How to set Full Recovery Model
USE master
GO
ALTER DATABASE Inventory SET RECOVERY FULL
GO

3. Bulk-logged Recovery Model

You can use bulk-logged recovery model when you are running very large operations or bulk operations. This recovery model reduces the transaction logging requirements for bulk operations. You can switch temporarily a database to bulk-logged recovery model when you are running bulk import or you are performing indexing operations on very large tables. It will increase performance using this recovery model rather than using full recovery model where each transactions are logged. This recovery model also retains transaction log records until they are backed up. Point-in-time recovery is not supported in bulk-logged.

Different Ways to Find Recovery Models in SQL Server


Today I was going through recovery models so thought to share different ways how we can find recovery models in SQL Server 2012.

Option 1:

Execute below query in query editor and find the recovery model.
SELECT name, recovery_model_desc FROM sys.databases
GO
01_RecoveryModel

Option 2:

Execute below query and check the recovery model in STATUS column.
EXEC sp_helpdb
GO

Option 3:

You can find the Recovery model through SSMS also as given in below path.
Go to Object Explorer –> Databases –> Right click on Database –> Select Properties –> SelectOptions Page
03_RecoveryModel

Option 4:

In Object Explorer, Select Databases node and Press F7, you can find the recovery model underRecovery Model column.
04_RecoveryModel

Option 5:

Put your database name in query and execute.
SELECT DATABASEPROPERTYEX ('DBName', 'RECOVERY') "Recovery Model"
GO
05_RecoveryModel

Option 6:

Right click on database and select Facets and you will find the detail in recovery model property.
06_RecoveryModel
If you know any other option, please do share with us. :)

SQL Server Database Tables for Beginners

We are going to learn about database tables like create table, insert into table, select table, rename table and drop table by referring T-SQL, Template Explorer and SQL Server Management Studio.

Basically a table is a combination of rows and columns filled with data in cells. This data is arranged in a manner that it becomes valuable information for us and collection of information altogether makes a database.

Note:  To create a database you need at least one primary data file and one log file.

For demonstration purpose we will refer AdventureWorks2012 database.

Create a Table

We can create table by T-SQL or SSMS as follows.

Syntax:

CREATE TABLE table_name ( column_name1 datatype (size), column_name2 datatype (size), . . . column_nameN datatype (size) )

Below you can refer a demo table named as tbl_Person.CREATE TABLE [tbl_Person]( [BusinessID] [int], [Title] [nvarchar](8), [FirstName] [nvarchar](50), [MiddleName] [nvarchar](50), [LastName] [nvarchar](50), [Country] [nvarchar](50) )

Suppose if you have forgot syntax for writing create table then no need to worry, SQL Server Management Studio provides Template Browser where you can drag Create Table template and drop to your query window. [refer Figure-1]





Figure 1: Template Explorer

You can access Template Explorer by pressing short key Ctrl+Alt+T or go to View –> clickTemplate Explorer in SQL Server Management Studio. Then navigate to Table –> Create Tabletemplate and drag and drop to your query window as shown below.-- 

-- Create table template -- 

USE <database, sysname, AdventureWorks2012> 
GO 
IF OBJECT_ID('<schema_name, sysname, dbo>.<table_name, sysname, sample_table>', 'U') IS NOT NULL 
DROP TABLE <schema_name, sysname, dbo>.<table_name, sysname, sample_table> 
GO 
CREATE TABLE <schema_name, sysname, dbo>.<table_name, sysname, sample_table> 
( <columns_in_primary_key, , c1> <column1_datatype, , int> <column1_nullability,, NOT NULL>, <column2_name, sysname, c2> <column2_datatype, , char(10)> <column2_nullability,, NULL>, <column3_name, sysname, c3> <column3_datatype, , datetime> <column3_nullability,, NULL>, CONSTRAINT <contraint_name, sysname, PK_sample_table> PRIMARY KEY (<columns_in_primary_key, , c1>) ) 
GO

or you can also create table by SSMS, you can right click on Tables under database and click onNew Table… where you have to specify column name, data type and size etc. [refer Figure-2]




Figure 2: Create Table by SSMS

You can check table details by T-SQL as in Figure-3. sp_help tbl_Person




Figure 3: Table Details

Insert Data in Table

You can insert data into table by following query.
INSERT INTO tbl_Person VALUES ( 100 ,'Mr.' ,'Roberto' ,'M' ,'Tamburello' ,'USA' )

Or you can insert records manually by SSMS as below.




Figure 4: Insert Rows

Note: You can change values for ‘Edit Top 200 Rows’ by changing settings in Tools Menu–>Options –> SQL Server Object Explorer –> Commands –> Value for Edit Top <n> Rows command

Select Records

You can view all available records in the table by querying.SELECT *FROM tbl_Person




Figure 5: Select Rows

Rename a Table

If you want to rename a table at any point of time due to some reason, you can do the same by T-SQL or by SSMS as mentioned below.

Syntax:sp_rename OldTableName, NewTableName

Here we will rename our existing table tbl_Person to new table name Person.sp_rename tbl_Person, Person

You can do the same by SSMS also navigating to Object Explorer, click Databases node then expand your database, go to Tables, right click on table and select Rename where you can type the new name. [refer Figure-6]




Figure 6: Rename Table


Drop a Table

If you want to completely drop a table, you can do the same by T-SQL or right click on table and click Delete in Object Explorer.

Additional Information

Database name is defined as nvarchar(128) with data type as ‘sysname’, you can simply create database with default values in a single line as:CREATE DATABASE BooksInfo

It will create the database with default path and values but if you want to create as per your requirements then you can create the same as given below. Here each file has it’s logical and physical file name.

CREATE DATABASE BooksInfo ON PRIMARY ( NAME = BooksInfo_Primary, FILENAME = 'C:\Database\BooksInfo.mdf', SIZE = 50MB, MAXSIZE = 500MB, FILEGROWTH = 10% ) LOG ON ( NAME = BooksInfo_Log, FILENAME = 'C:\DatabaseLog\BooksInfo_log.ldf', SIZE = 10MB, MAXSIZE = UNLIMITED, FILEGROWTH = 10MB )

It will create primary data file as BooksInfo.mdf and log file as BooksInfo_log.ldf but if you want to include one file group also then you can create the database as given below.

CREATE DATABASE BooksInfo ON PRIMARY ( NAME = BooksInfo_Primary, FILENAME = 'C:\Database\BooksInfo.mdf', SIZE = 50MB, MAXSIZE = 500MB, FILEGROWTH = 10% ), FILEGROUP BooksInfo_G1 ( NAME = BooksFileGroup1, FILENAME = 'C:\Database\BooksInfo_G1.ndf', SIZE = 50MB, MAXSIZE = 500MB, FILEGROWTH = 10% ) LOG ON ( NAME = BooksInfo_Log, FILENAME = 'C:\DatabaseLog\BooksInfo_log.ldf', SIZE = 10MB, MAXSIZE = UNLIMITED, FILEGROWTH = 10MB )




Now your database will be created with one file group also as BooksInfo_G1.ndf. You can also mention collation with create database command but if you have not specified it then it will consider collation of your SQL Server instance as default.
Create Database by SSMS

To create database with SQL Server Management Studio go to Object Explorer –> right click on Databases –> select New Database –> enter a database name and click OK.

It will create a database with default values and path. If you want you can change the path and default values in new database window and add filegroup as well, by default primary filegroup is set.

Permissions required to Create Database

You need following permissions to create a database.

– CREATE DATABASE,
– CREATE ANY DATABASE
– ALTER ANY DATABASE

Configure Network Drive Visible for SQL Server During Backup and Restore Using SSMS

Introduction

Most of the Development and Test Database Servers will not have enough disk space to store both the database and backup files in order to perform the periodic database refreshes. In such scenarios, the best option will be to store the database backup files in a mapped network drive and perform the database restores from the mapped drive. However, things can become really complicated when the developer tries to restore the database using SSMS and they couldn't locate the respective mapped drive under Locate Backup File window as shown in the snippet below.
Locate Backup Files in SQL Server
In SQL Server Management Studio, if you try to browse the backup files, you will only see the local drives available to SQL Server Database Engine. In this article we will take a look at the approach on How to Configure SQL Server to Display Network Path Visible to SSMS to Perform Database Backup or Restore Commands.

How to Map a Network Drive

By default, a network share is not visible to SQL Server Database Engine. Hence, you will have to mark Network Share as a Mapped Network Drive using the using the Map Network Drive feature of the Operating System. Refer the below screenshots which highlights How to Create a Mapped Network Drive.
How to Map Network Drive in SQL Server


Specify Drive Letter for Network Drive and Share Folder Path to Map Network Drive as Local Drive
Once the Network Drive is mapped successfully the next Step will be to identify the network drive within SQL Server. This can be achieved by using XP_CMDSHELL command. For more information, see How to Enable and Disable XP_CMDSHELL command in SQL Server.

How to Map Network Drive in SQL Server

In the below script replace Drive Letter and Share Path with values in your environment to Map Network Drive in SQL Server.
EXEC XP_CMDSHELL 'net use Z: \\RemoteServerName\ShareName'

How to Verify Mapped Network Drive Mapping in SQL Server

Execute the below query by replacing the Dirve Letter with the Drive Letter which you have provided in your environment.
EXEC XP_CMDSHELL 'Dir Z:'
Once you have executed the above script successfully you will be to see "Z Drive" under Locate Backup File as shown in the below snippet.
Mapped Drive Visible in SQL Server Management Studio to Perform Backup and Restore

How to Delete Mapped Network Drive Mapping in SQL Server

Execute the below TSQL code to Delete the Mapped Network Drive from SQL Server.
EXEC XP_CMDSHELL 'net use Z: /delete'

Action Item

  • You can very well provide the full network location of the file in "File Name" field of "Locate Backup File" window. The approach mentioned in this article is only required if you wish to perform backup or restore using SQL Server Management Studio.
  • DBAs or Developers can very well backup or restore database from Network Share without Mapping the drive. This is only required if you wish to perform backup or restore using SQL Server Management Studio.
  • Once you have completed the Backup or Restore as a Best Practice on should disable XP_CMDSHELL in SQL Server. For more information see, How to Enable and Disable XP_CMDSHELL command in SQL Server
  • Learn more about SQL Server Security Best Practices.


Read more: http://www.mytechmantra.com/LearnSQLServer/Configure-Network-Drive-Visible-for-SQL-Server-During-Backup-and-Restore-Using-SSMS/#ixzz3h4a2jTNH
Follow us: @MyTechMantra on Twitter | MyTechMantra on Facebook

Uninstalling SQL Server 2008

By: Editor 
March 26, 2009

Page: 1/4 

Introduction

This article is a step by step guide which can be used by database administrators to uninstall SQL Server 2008 Enterprise Edition.
"This article has a total of 4 pages including this page. Follow the links below to open all 4 pages in a seperate window to learn how to Uninstall SQL Server 2008. Page 1Page 2Page 3Page 4"
1. Click Start | Control Panel | Add or Remove Programs. In the Add or Remove Programswindows select Microsoft SQL Server 2008 as shown in the snippet below and Click Change/Remove button.
Add or Remove Programs

2. Once you click on Change/Remove button it will popup SQL Server 2008 windows as shown in the snippet below. There are three options basically available and they are Add, Repair and Remove.
  • Add:- This option can be used by database administrators if they want to add any new feature of SQL Server 2008 which you may not have installed previously. The different features can be adding Analysis Services, Integration Services , Reporting Services or Replication etc.
  • Repair:-This option can be used by database administrators if they want to repair SQL Server 2008 product.
  • Remove:- This option can be used by database administrators if they want to remove SQL Server 2008 product. This is the option which you need to select to Uninstall SQL Server 2008.

SQL Server 2008 Add, Repair or Remove Screen
3. Once you click on Remove option, you will see a popup screen informing you to wait for a while till SQL Server 2008 Setup is processing the current user request.
4. In SQL Server 2008 Setup Support Rules screen SQL Server setup program identifies problem which can occur when you uninstall SQL Server. If there are no issues encountered they you will see Passed message against each rule. Click OK to continue with the uninstallation.

SQL Server 2008 Setup Support Rules Screen 

5. In Select Instance screen select the SQL Server Instance from where you need to remove features. This can be done by selecting the instance name from the drop down list as shown in the snippet below. Click Next to continue with the uninstallation process.

Select SQL Server Instance From where you want to uninstall features 

6. In the Select Features screen choose the feature which needs to be removed and click Next to continue with the uninstallation process.
 


7. In the Removal Rules screen you could see that SQL Server setup program is checking internally whether the uninstallation process will be successful or not. You will be able to see the status for Removal architecture mismatch as true if there are no issues in uninstalling SQL Server 2008. Click Next to continue with the uninstallation process.


8. In the Ready to Remove screen SQL Server 2008 setup will ask you to verify the SQL Server 2008 features which will be removed. click Next to continue with the uninstallation process.

MORE SQL SERVER ARTICLES

ALSO READ ... HOW TO INSTALL SQL SERVER 2008 R2 
HOW TO INSTALL SQL SERVER 2012


SIGN UP TODAY FOR MYTECHMANTRA.COM NEWSLETTER
LIKE US ON FACEBOOK   |  FOLLOW US ON TWITTER

 
9. Once the requested features are removed, the Removal Progress screen which will have the Success or Failure message for each and every single feature which it has removed. Click Next to complete the uninstallation process.





10. In the Complete screen you will be able to see “Your SQL Server 2008 removal completed successfully”. Click Close to exit Remove SQL Server 2008 setup.

 

Conclusion

In this article you have seen the steps which database administrator needs to follow to uninstall an instance of SQL Server 2008 manually.


Read more: http://www.mytechmantra.com/LearnSQLServer/Uninstalling_SQL_Server_2008_P4.html#ixzz3h4tKB1c5
Follow us: @MyTechMantra on Twitter | MyTechMantra on Facebook



Read more: http://www.mytechmantra.com/LearnSQLServer/Uninstalling_SQL_Server_2008_P1.html#ixzz3h4srz6D4
Follow us: @MyTechMantra on Twitter | MyTechMantra on Facebook