/* ------------------------ My Meta Content Here SEO ------------------------ */

Pages

Main Menu

Wednesday, May 21, 2014

Handling deadlock conditions in sql server


First create database structure: Run the following complete query:

--- db script start from here ---

utm_source=dailynewsletter&utm_medium=email&utm_content=headline&utm_campaign=20140325

USE [master]
GO
CREATE DATABASE TestDB
 ON PRIMARY 
( NAME = N'TestDB', FILENAME = N'E:\MSSQL\TestDB.mdf' , SIZE = 10240KB , MAXSIZE = UNLIMITED, 
FILEGROWTH = 1024KB )
 LOG ON 
( NAME = N'TestDB_log', FILENAME = N'E:\MSSQL\TestDB_log.ldf' , SIZE = 1024KB , MAXSIZE = UNLIMITED, 
FILEGROWTH = 1024KB)
GO

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

USE [master]
GO
/****** Object:  Database [TESTDB]    Script Date: 05/21/2014 15:22:06 ******/
CREATE DATABASE [TESTDB] ON  PRIMARY 
( NAME = N'TESTDB', FILENAME = N'D:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\TESTDB.mdf' , SIZE = 2048KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB )
 LOG ON 
( NAME = N'TESTDB_log', FILENAME = N'D:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\TESTDB_log.ldf' , SIZE = 1024KB , MAXSIZE = 2048GB , FILEGROWTH = 10%)
GO
ALTER DATABASE [TESTDB] SET COMPATIBILITY_LEVEL = 100
GO
IF (1 = FULLTEXTSERVICEPROPERTY('IsFullTextInstalled'))
begin
EXEC [TESTDB].[dbo].[sp_fulltext_database] @action = 'enable'
end
GO
ALTER DATABASE [TESTDB] SET ANSI_NULL_DEFAULT OFF
GO
ALTER DATABASE [TESTDB] SET ANSI_NULLS OFF
GO
ALTER DATABASE [TESTDB] SET ANSI_PADDING OFF
GO
ALTER DATABASE [TESTDB] SET ANSI_WARNINGS OFF
GO
ALTER DATABASE [TESTDB] SET ARITHABORT OFF
GO
ALTER DATABASE [TESTDB] SET AUTO_CLOSE OFF
GO
ALTER DATABASE [TESTDB] SET AUTO_CREATE_STATISTICS ON
GO
ALTER DATABASE [TESTDB] SET AUTO_SHRINK OFF
GO
ALTER DATABASE [TESTDB] SET AUTO_UPDATE_STATISTICS ON
GO
ALTER DATABASE [TESTDB] SET CURSOR_CLOSE_ON_COMMIT OFF
GO
ALTER DATABASE [TESTDB] SET CURSOR_DEFAULT  GLOBAL
GO
ALTER DATABASE [TESTDB] SET CONCAT_NULL_YIELDS_NULL OFF
GO
ALTER DATABASE [TESTDB] SET NUMERIC_ROUNDABORT OFF
GO
ALTER DATABASE [TESTDB] SET QUOTED_IDENTIFIER OFF
GO
ALTER DATABASE [TESTDB] SET RECURSIVE_TRIGGERS OFF
GO
ALTER DATABASE [TESTDB] SET  DISABLE_BROKER
GO
ALTER DATABASE [TESTDB] SET AUTO_UPDATE_STATISTICS_ASYNC OFF
GO
ALTER DATABASE [TESTDB] SET DATE_CORRELATION_OPTIMIZATION OFF
GO
ALTER DATABASE [TESTDB] SET TRUSTWORTHY OFF
GO
ALTER DATABASE [TESTDB] SET ALLOW_SNAPSHOT_ISOLATION OFF
GO
ALTER DATABASE [TESTDB] SET PARAMETERIZATION SIMPLE
GO
ALTER DATABASE [TESTDB] SET READ_COMMITTED_SNAPSHOT OFF
GO
ALTER DATABASE [TESTDB] SET HONOR_BROKER_PRIORITY OFF
GO
ALTER DATABASE [TESTDB] SET  READ_WRITE
GO
ALTER DATABASE [TESTDB] SET RECOVERY SIMPLE
GO
ALTER DATABASE [TESTDB] SET  MULTI_USER
GO
ALTER DATABASE [TESTDB] SET PAGE_VERIFY CHECKSUM
GO
ALTER DATABASE [TESTDB] SET DB_CHAINING OFF
GO
USE [TESTDB]
GO
/****** Object:  Table [dbo].[Sales]    Script Date: 05/21/2014 15:22:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING OFF
GO
CREATE TABLE [dbo].[Sales](
[EmpId] [int] NULL,
[Yr] [int] NULL,
[Sales] [money] NULL,
[CreatedDate] [datetime] NOT NULL,
[AddedBy] [varchar](200) NULL,
[CreatedBy] [varchar](200) NULL,
[CreatedOn] [datetime] NOT NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[SalaryType]    Script Date: 05/21/2014 15:22:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[SalaryType](
[ID] [varchar](10) NULL,
[Descrp] [varchar](50) NULL,
[CreatedDate] [datetime] NOT NULL
) ON [PRIMARY]
SET ANSI_PADDING OFF
ALTER TABLE [dbo].[SalaryType] ADD [AddedBy] [varchar](200) NULL
ALTER TABLE [dbo].[SalaryType] ADD [DeletedBy] [varchar](200) NULL
ALTER TABLE [dbo].[SalaryType] ADD [CreatedBy] [varchar](200) NULL
ALTER TABLE [dbo].[SalaryType] ADD [CreatedOn] [datetime] NOT NULL
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[Customers]    Script Date: 05/21/2014 15:22:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Customers](
[CustomerId] [int] IDENTITY(1,1) NOT NULL,
[CustomerCode] [nvarchar](10) NOT NULL,
[CustomerName] [nvarchar](50) NOT NULL,
[CustomerAddress] [nvarchar](50) NOT NULL,
[LastModified] [datetime] NOT NULL,
PRIMARY KEY CLUSTERED 
(
[CustomerId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET IDENTITY_INSERT [dbo].[Customers] ON
INSERT [dbo].[Customers] ([CustomerId], [CustomerCode], [CustomerName], [CustomerAddress], [LastModified]) VALUES (2, N'A15C6E', N'John Doe', N'Evergreen 1234', CAST(0x0000A30300D27AAD AS DateTime))
INSERT [dbo].[Customers] ([CustomerId], [CustomerCode], [CustomerName], [CustomerAddress], [LastModified]) VALUES (3, N'A15C6E', N'John Doe', N'Evergreen 1234', CAST(0x0000A30300D2860D AS DateTime))
INSERT [dbo].[Customers] ([CustomerId], [CustomerCode], [CustomerName], [CustomerAddress], [LastModified]) VALUES (5, N'A15C6E', N'John Doe', N'Evergreen 1234', CAST(0x0000A30300D632CE AS DateTime))
INSERT [dbo].[Customers] ([CustomerId], [CustomerCode], [CustomerName], [CustomerAddress], [LastModified]) VALUES (6, N'A15C6E', N'John Doe', N'Evergreen 1234', CAST(0x0000A30300D63E46 AS DateTime))
INSERT [dbo].[Customers] ([CustomerId], [CustomerCode], [CustomerName], [CustomerAddress], [LastModified]) VALUES (7, N'A15C6E', N'John Doe', N'Evergreen 1234', CAST(0x0000A33200FC6957 AS DateTime))
SET IDENTITY_INSERT [dbo].[Customers] OFF
/****** Object:  Default [DF__Customers__LastM__03317E3D]    Script Date: 05/21/2014 15:22:06 ******/
ALTER TABLE [dbo].[Customers] ADD  DEFAULT (getdate()) FOR [LastModified]
GO

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

USE TestDB
GO
IF OBJECT_ID('dbo.Customers','U') IS NOT NULL
  DROP TABLE dbo.Customers
GO
CREATE TABLE dbo.Customers(
  CustomerId        INT NOT NULL IDENTITY(1,1),
  CustomerCode      NVARCHAR(10) NOT NULL,
  CustomerName      NVARCHAR(50) NOT NULL,
  CustomerAddress   NVARCHAR(50) NOT NULL,
  LastModified  DATETIME NOT NULL DEFAULT  GETDATE()
  PRIMARY KEY CLUSTERED (CustomerId)
)
GO

---RUN This query in two different windows
USE TestDB
GO
BEGIN TRANSACTION
INSERT INTO dbo.Customers ( CustomerCode ,
          CustomerName ,
          CustomerAddress
        )
VALUES  ( N'A15C6E' ,
          N'John Doe' ,
          N'Evergreen 1234'
        )
WAITFOR DELAY '00:00:10'
SELECT * FROM dbo.Customers
COMMIT TRANSACTION

USE TestDB
GO
TRUNCATE TABLE dbo.Customers

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

USE TestDB
GO
DECLARE @RetryCount INT
DECLARE @Success    BIT
SELECT @RetryCount = 1, @Success = 0
WHILE @RetryCount < =  3 AND @Success = 0
BEGIN
   BEGIN TRY
      BEGIN TRANSACTION
      -- This line is to show you on which execution 
      -- we successfully commit.
      SELECT CAST (@RetryCount AS VARCHAR(5)) +  'st. Attempt'
  
      INSERT  INTO dbo.Customers
      ( CustomerCode ,
      CustomerName ,
      CustomerAddress
      )
      VALUES  ( N'A15C6E' ,
      N'John Doe' ,
      N'Evergreen 1234'
      )

      -- This Delay is set in order to simulate failure
      -- DO NOT USE IN REAL CODE!
      WAITFOR DELAY '00:00:05'
  
      SELECT * FROM dbo.Customers
  
      COMMIT TRANSACTION
  
      SELECT 'Success!'
      SELECT @Success = 1 -- To exit the loop
   END TRY

   BEGIN CATCH
      ROLLBACK TRANSACTION

      SELECT  ERROR_NUMBER() AS [Error Number],
      ERROR_MESSAGE() AS [ErrorMessage];     
  
      -- Now we check the error number to 
      -- only use retry logic on the errors we 
      -- are able to handle.
      --
      -- You can set different handlers for different 
      -- errors
      IF ERROR_NUMBER() IN (  1204, -- SqlOutOfLocks
                              1205, -- SqlDeadlockVictim
                              1222 -- SqlLockRequestTimeout
                              )
      BEGIN
            SET @RetryCount = @RetryCount + 1  
            -- This delay is to give the blocking 
            -- transaction time to finish.
            -- So you need to tune according to your 
            -- environment
            WAITFOR DELAY '00:00:02'  
      END 
      ELSE    
      BEGIN
           --THROW 50001, 'Your custom error message.', 1;
            -- If we don't have a handler for current error
            -- then we throw an exception and abort the loop
            --THROW 50001; -- THROW Statement is introduced in SQL Server 2012
            --RAISERROR('TEST',12,1);
           
            DECLARE @ErrorMessage NVARCHAR(4000);
DECLARE @ErrorSeverity INT;
DECLARE @ErrorState INT;

SELECT 
@ErrorMessage = ERROR_MESSAGE(),
@ErrorSeverity = ERROR_SEVERITY(),
@ErrorState = ERROR_STATE();

RAISERROR (@ErrorMessage, -- Message text.
  @ErrorSeverity, -- Severity.
  @ErrorState -- State.
  );                
            
      END
   END CATCH
END

-----------------------------------------------------------------------------------------------------
Reference:- http://www.mssqltips.com/sqlservertip/3188/implementing-sql-server-transaction-retry-logic-for-failed-transactions/?



No comments:

Post a Comment

My Blog List