Sunday 5 July 2015

Understanding Lockings in SQL Server

 




Locking optimizer hints

SQL Server 7.0/2000 supports the following Locking optimizer hints:

  • NOLOCK
  • HOLDLOCK
  • UPDLOCK
  • TABLOCK
  • PAGLOCK
  • TABLOCKX
  • READCOMMITTED
  • READUNCOMMITTED
  • REPEATABLEREAD
  • SERIALIZABLE
  • READPAST
  • ROWLOCK


  • NOLOCK is also known as "dirty reads". This option directs SQL Server not to issue shared locks and not to honor exclusive locks. So, if this option is specified, it is possible to read an uncommitted transaction. This results in higher concurrency and in lower consistency.

    HOLDLOCK directs SQL Server to hold a shared lock until completion of the transaction in which HOLDLOCK is used. You cannot use HOLDLOCK in a SELECT statement that includes the FOR BROWSE option. HOLDLOCK is equivalent to SERIALIZABLE.

    UPDLOCK instructs SQL Server to use update locks instead of shared locks while reading a table and holds them until the end of the command or transaction.

    TABLOCK takes a shared lock on the table that is held until the end of the command. If you also specify HOLDLOCK, the lock is held until the end of the transaction.

    PAGLOCK is used by default. Directs SQL Server to use shared page locks.

    TABLOCKX takes an exclusive lock on the table that is held until the end of the command or transaction.

    READCOMMITTED
    Perform a scan with the same locking semantics as a transaction running at the READ COMMITTED isolation level. By default, SQL Server operates at this isolation level.

    READUNCOMMITTED
    Equivalent to NOLOCK.

    REPEATABLEREAD
    Perform a scan with the same locking semantics as a transaction running at the REPEATABLE READ isolation level.

    SERIALIZABLE
    Perform a scan with the same locking semantics as a transaction running at the SERIALIZABLE isolation level. Equivalent to HOLDLOCK.

    READPAST
    Skip locked rows. This option causes a transaction to skip over rows locked by other transactions that would ordinarily appear in the result set, rather than block the transaction waiting for the other transactions to release their locks on these rows. The READPAST lock hint applies only to transactions operating at READ COMMITTED isolation and will read only past row-level locks. Applies only to the SELECT statement.
    You can only specify the READPAST lock in the READ COMMITTED or REPEATABLE READ isolation levels.

    ROWLOCK
    Use row-level locks rather than use the coarser-grained page- and table-level locks.

    You can specify one of these locking options in a SELECT statement.
    This is the example:

    SELECT au_fname FROM pubs..authors (holdlock)



    0

    Working with Batch or Command Files



    Using batch files as a deployment scripts
    Batch files or Command [.cmd] files are still used for deployment purpose in many organizations.

    Batch files are simple text files containing some lines with commands that get executed in sequence, one after the other. These files have the special extension BAT or CMD. Files of this type are recognized and executed through an interface (sometimes called a shell) provided by a system file called the command interpreter. 

    These are using to trigger SQL Scripts, copy files etc ... This article explains how to create batch files for deployment purpose.

    Creating a simple batch/cmd file:

    Below file executes a SQL Script file from a specific path, this file accepts server and database as parameters:

    @echo off
    set /p sname= Please enter the servername:
    set /p dbname= Please enter the databasename:
    set /p pwd= Please enter the password:
    sqlcmd -E -S %sname% -D %dbname% -P %PWD% -i "C:\location\your query.sql" -b)

    With Error handling:

    echo off
    setlocal enabledelayedexpansion
    set /p servername=Enter DB Servername :
    set /p dbname=Enter Database Name :
    set /p spath=Enter Script Path :
    set hr=%time:~0,2%
    if "%hr:~0,1%" equ " " set hr=0%hr:~1,1%
    set logfilepath= %spath%\output_%date:~-4,4%%date:~-10,2%%date:~-7,2%_%hr%%time:~3,2%%time:~6,2%.log
    set cmd='dir %spath%\*.sql /b/s'
    FOR /f %%G IN (%cmd%) DO (
    echo ******PROCESSING %%G FILE******
    echo ******PROCESSING %%G FILE****** >> %logfilepath%
    SQLCMD -S%servername% -E -d%dbname% -b -i%%G >> %logfilepath%
    IF !ERRORLEVEL! NEQ 0 GOTO :OnError
    )
    GOTO :Success

    :OnError
    echo ERROR ERROR ERROR
    echo One\more script(s) failed to execute, terminating bath.
    echo Check output.log file for more details
    EXIT /b

    :Success
    echo ALL the scripts deployed successfully!!
    EXIT /b





    0

    TSQL Queries Search for SQL Objects

    Frequently used SQL Queries

     
    There are many SQL Queries which are used frequently as a part of our SDLC, I am trying to consolidate all and keep at one place. Hope this helps!


    Search for a tablename in all SQL Objects:
    There are different ways of searching for a text in all SQL Objects, below are few methods:

    SELECT Name FROM sys.procedures WHERE OBJECT_DEFINITION(OBJECT_ID) LIKE '%SEARCHSTRING%'

    DECLARE @Search varchar(255)
    SET @Search='SearchString'
    SELECT DISTINCT o.name AS Object_Name,o.type_desc FROM sys.sql_modules m INNER JOIN sys.objects o ON m.object_id=o.object_id WHERE m.definition Like '%'+@Search+'%' ORDER BY 2,1


    Another simple way of doing this,
    SELECT DISTINCT OBJECT_NAME(id) FROM syscomments WHERE [text] LIKE '%SearchString%'


    Get all Tables across all databases in a Server:

    There are few instances where we want to list all the tables in all databases in a database server,

    SET NOCOUNT ON
    DECLARE @AllTables table (CompleteTableName nvarchar(4000))
    INSERT INTO @AllTables (CompleteTableName) EXEC sp_msforeachdb 'select @@SERVERNAME+''.''+''?''+''.''+s.name+''.''+t.name from [?].sys.tables t inner join sys.schemas s on t.schema_id=s.schema_id'
    SET NOCOUNT OFF

    --Get Result
    SELECT * FROM @AllTables ORDER BY 1


     
    1