Showing posts with label MS SQL Server. Show all posts
Showing posts with label MS SQL Server. Show all posts

Friday, February 9, 2018

Batch scripting - SQL Server - Execute all sql files from a folder

Description:
In my project code base, I have a structure for all database objects (stored procedure, functions, trigger etc.) as well as some upgrade scripts. Need a nice way to deploy all the database scripts rather manually execute one by one.

Environment information:
1. Windows Batch script
2. SQL Server 2014

Script:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
@ECHO OFF
REM Database connection info
SET databaseName=db_name
SET databaseServer=db_server
SET databaseUserName=db_user
SET databasePassword=db_password

REM Location of scripts. Multiple folders can be specified by giving space in between and enclosed with quotation.
REM This script will go through only one level of sub folders and execute all .sql files
SET scriptLocation="location1" "location2"



REM -----------------------------------------------------------
REM - Logic 
REM -----------------------------------------------------------

SET initialLocation=%cd%

FOR %%e IN (%scriptLocation%) DO (
 @ECHO ------------------------
 @ECHO %%e
 @ECHO ------------------------
 IF EXIST %%e (
  CALL :executeScripts %%e
 
  FOR /D %%i IN (%%e\*) DO (
   @ECHO ------------------------
   @ECHO %%i
   @ECHO ------------------------
   CALL :executeScripts "%%i"
   
  )
 ) 
)

CD %initialLocation%
PAUSE


:: This function execute all the scripts from given path
:executeScripts
FOR %%G IN (%1\*.sql) DO (
 @ECHO %%~nxG  
 sqlcmd /S %databaseServer%  /d %databaseName%  -U %databaseUserName%  -P %databasePassword% -i"%%G"
)
EXIT /B 0

Saturday, December 9, 2017

Java - JDBC - use parameterized query with IN clause having dynamic list

Background: I needed to execute query with IN clause where the list is dynamic in nature. The database is sql server 2012 and the driver doesn't support java.sql.Statement.setArray(1, java.sql.Array) yet. Had to come up with the below trick to make it work. In the example, tried it on both SELECT and DELETE. Code is written in Java and tried on SQL server 2012. 

Script to create table and populate data:


CREATE TABLE employee (id INT, name VARCHAR(1000));

INSERT INTO employee (id, name) VALUES(1, 'First');
INSERT INTO employee (id, name) VALUES(2, 'Second');
INSERT INTO employee (id, name) VALUES(3, 'Third');
INSERT INTO employee (id, name) VALUES(4, 'Fourth');

Java Class:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class TestParameterizedIN {

 // JDBC driver name and database URL
   static final String JDBC_DRIVER = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
   static final String DB_URL = "jdbc:sqlserver://localhost:1433;databaseName=testingGround";

   // Database credentials
   static final String USER = "***";
   static final String PASS = "***";

   public static void main(String[] args) {
     Connection conn = null;
     PreparedStatement stmt = null;
     try {
       // Register JDBC driver
       Class.forName(JDBC_DRIVER);

       // Open a connection
       System.out.println("Connecting to database...");
       conn = DriverManager.getConnection(DB_URL, USER, PASS);

       //Fetch records
       System.out.println("Fetching data...");
       int[] ids = new int[]{1,2,3};//IDs of records to select data
       String sql = "";
       for(int each=0; each<ids.length; each++){
        if(each == 0)
         sql = "SELECT id, name FROM employee WHERE ID IN (?";
        else
         sql += " ,?";
       }
       sql += ")";
       
       System.out.println("--------------------");
       stmt = conn.prepareStatement(sql);
       for(int each=0; each<ids.length; each++){
        stmt.setInt(each+1, ids[each]);
       }
       try(ResultSet rs = stmt.executeQuery()){
      // Extract data from result set
        while (rs.next()) {
          // Retrieve by column name
          int id = rs.getInt("id");
          String name = rs.getString("name");

          System.out.print("ID: " + id);
          System.out.print(", Name: " + name);
          System.out.println("");
        }
       }
       System.out.println("--------------------");
       stmt.close();
       
       //Delete records
       System.out.println("Delete records...");
       sql = "";
       for(int each=0; each<ids.length; each++){
        if(each == 0)
         sql = "DELETE FROM employee WHERE ID IN (?";
        else
         sql += " ,?";
       }
       sql += ")";
       
       stmt = conn.prepareStatement(sql);
       for(int each=0; each<ids.length; each++){
        stmt.setInt(each+1, ids[each]);
       }
       System.out.println(stmt.executeUpdate()+" records are deleted");
       
     } catch (SQLException se) {
       se.printStackTrace();
     } catch (Exception e) {
       e.printStackTrace();
     } finally {
       // finally block used to close resources
       try {
         if (stmt != null)
           stmt.close();
       } catch (SQLException se2) {
       }
       try {
         if (conn != null)
           conn.close();
       } catch (SQLException se) {
         se.printStackTrace();
       }
     }
   }
}

Output of the class execution:

Connecting to database...
Fetching data...
--------------------
ID: 1, Name: First
ID: 2, Name: Second
ID: 3, Name: Third
--------------------
Delete records...
3 records are deleted

Note:

  1. Used mssql-jdbc-6.2.2.jre8.jar for SQL Server driver.
  2. Will work on another blog to try out java.sql.Statement.setArray(1, java.sql.Array), may be on HSQLDB.


Monday, November 20, 2017

MS SQL Server - Query - Concatenate data from multiple records in a GROUP BY query

Problem: Need to find out the employees reporting to a manager and create a comma separated list of names. Data will look like table-01.











Expected output would look like:
Table-01:

Solution-01: using FOR XML PATH

-- Create table
CREATE TABLE 
#employeeManagerAssociation (managerID INT, employeeID INT, firstName VARCHAR(100), lastName VARCHAR(100))
;

-- Insert data
INSERT INTO #employeeManagerAssociation (managerID,employeeID,firstName,lastName) VALUES (1, 101,'E1_First', 'E1_Last');
INSERT INTO #employeeManagerAssociation (managerID,employeeID,firstName,lastName) VALUES (1,102,'E2_First', 'E2_Last');
INSERT INTO #employeeManagerAssociation (managerID,employeeID,firstName,lastName) VALUES (2,103,'E3_First', 'E3_Last');
INSERT INTO #employeeManagerAssociation (managerID,employeeID,firstName,lastName) VALUES (2,104,'E4_First', 'E4_Last');
INSERT INTO #employeeManagerAssociation (managerID,employeeID,firstName,lastName) VALUES (3,105,'E5_First', 'E5_Last');

SELECT 
  managerID,
  STUFF((
    SELECT ', ' + firstName + ' ' + lastName 
    FROM #employeeManagerAssociation 
    WHERE managerID = main.managerID
    FOR XML PATH('')
)--,TYPE).value('(./text())[1]','VARCHAR(MAX)')
  ,1,2,'') AS NameValues
FROM #employeeManagerAssociation main
GROUP BY managerID

-- Delete temporary table

DROP TABLE #employeeManagerAssociation



Tuesday, October 14, 2014

SQL Server - Coding - Update data in tables related by foreign constraint

Environment: SQL Server 2008

Background: I need to update id column value of a table which has corresponding data in a child table and integrity enforced by foreign key constraint. Relationship between tables and data excerpt present below. Need to change 'ROLE_EXEMPTION' with value 'ROLE_AMLM_QA1_EXEMPTION'.

Table relationship:
















Data in tables:















Script to fulfill the need:

DECLARE @changedValue VARCHAR(100) = 'ROLE_AMLM_QA1_EXCEMPTION',
@originalValue VARCHAR(100) = 'ROLE_EXEMPTION'
;

-- Disable all table constraints
ALTER TABLE wk_sec_role_resource_mapping NOCHECK CONSTRAINT ALL;

-- Update parent table record
UPDATE wk_sec_roles SET role_id=@changedValue WHERE role_id=@originalValue;
-- Update child table record
UPDATE wk_sec_role_resource_mapping SET role_FK=@changedValue WHERE role_FK=@originalValue;

-- Enable all table constraints

ALTER TABLE wk_sec_role_resource_mapping CHECK CONSTRAINT ALL;


Necessary info:

-- Disable all table constraints
ALTER TABLE MyTable NOCHECK CONSTRAINT ALL

-- Enable all table constraints
ALTER TABLE MyTable CHECK CONSTRAINT ALL

-- Disable single constraint
ALTER TABLE MyTable NOCHECK CONSTRAINT MyConstraint

-- Enable single constraint
ALTER TABLE MyTable CHECK CONSTRAINT MyConstraint
-- disable all constraints

EXEC sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"

Wednesday, June 4, 2014

SQL Server - Setup - enable/disable SNAPSHOT isolation level

Environment:
1. SQL Server 2008

Background:
I need a script which would change isolation level to SNAPSHOT on current database. I tried to use CURRENT to make it work without much success. Instead used DB_NAME() built-in function to get the current database name and executed alter command as run time query.

Script snippet:

DECLARE @dbName VARCHAR(100) = '';
SELECT @dbName=DB_NAME();
IF ISNULL(@dbName, '') <> ''
BEGIN
DECLARE @cmd NVARCHAR(100) = 'ALTER DATABASE '+@dbName+'  SET ALLOW_SNAPSHOT_ISOLATION ON';
EXECUTE sp_executesql @cmd;
END;
GO


Helpful commands:


To enable:
ALTER DATABASE ABC SET ALLOW_SNAPSHOT_ISOLATION ON;

To disable:
ALTER DATABASE ABC SET ALLOW_SNAPSHOT_ISOLATION OFF;


How to check database isolation settings:
SELECT name
        , s.snapshot_isolation_state
        , snapshot_isolation_state_desc
        , is_read_committed_snapshot_on
        , recovery_model
        , recovery_model_desc
        , collation_name

FROM sys.databases s

Friday, May 16, 2014

SQL Server - Coding - Find out tables those are related

Environment: Tried on SQL Server 2008

First Query: Show all tables from the database where parent-child relationship is present 

SELECT
OBJECT_NAME(rkeyid) parent_table,
OBJECT_NAME(fkeyid) child_table,
OBJECT_NAME(constid) fkey_name,
c1.name fkey_col,
c2.name ref_keycol
FROM SYS.SYSFOREIGNKEYS s
INNER JOIN SYS.SYSCOLUMNS c1
ON ( s.fkeyid = c1.id and s.fkey = c1.colid )
INNER JOIN SYSCOLUMNS c2
ON ( s.rkeyid = c2.id and s.rkey = c2.colid )

ORDER BY parent_table,child_table
;


Second Query: Show all parent tables of a particular table

SELECT
OBJECT_NAME(rkeyid) parent_table,
OBJECT_NAME(fkeyid) child_table,
OBJECT_NAME(constid) fkey_name,
c1.name fkey_col,
c2.name ref_keycol
FROM SYS.SYSFOREIGNKEYS s
INNER JOIN SYS.SYSCOLUMNS c1
ON ( s.fkeyid = c1.id and s.fkey = c1.colid )
INNER JOIN SYSCOLUMNS c2
ON ( s.rkeyid = c2.id and s.rkey = c2.colid )
WHERE OBJECT_NAME(fkeyid) = '
'


ORDER BY parent_table,child_table


Third Query: Show all child tables of a particular table

SELECT
OBJECT_NAME(rkeyid) parent_table,
OBJECT_NAME(fkeyid) child_table,
OBJECT_NAME(constid) fkey_name,
c1.name fkey_col,
c2.name ref_keycol
FROM SYS.SYSFOREIGNKEYS s
INNER JOIN SYS.SYSCOLUMNS c1
ON ( s.fkeyid = c1.id and s.fkey = c1.colid )
INNER JOIN SYSCOLUMNS c2
ON ( s.rkeyid = c2.id and s.rkey = c2.colid )
WHERE OBJECT_NAME(rkeyid) = '
'

ORDER BY parent_table,child_table


Reference:
1. Concept is taken from an online article, unfortunately don't have link

Tuesday, February 25, 2014

Design - Java + SQL Server - Discussion about file based vs database storage for file upload

Background:
Below investigation done considering java application with SQL Server as back-end. Java - 1.6 and SQL Server - 2008 r2. 


1. Comparison table (Source-01, Source-04)

Comparison point
Storage solution
File server / file system
SQL Server (using varbinary(max))
FILESTREAM
Maximum BLOB size
NTFS volume size
2 GB – 1 bytes
NTFS volume size
File Size recommendation
>1MB
<256kb o:p="">

>1MB
Note: File size between >256KB and <1mb b="" is="" need="" project="" subject="" to="">Source-01
)
Streaming performance of large BLOBs
Excellent
Poor
Excellent
Security
Manual ACLs
Integrated
Integrated + automatic ACLs
Cost per GB
Low
High
Low
Manageability
Difficult
Integrated
Integrated
Integration with structured data
Difficult
Data-level consistency
Data-level consistency
Application development and deployment
More complex
More simple
More simple
Recovery from data fragmentation
Excellent
Poor
Excellent
Performance of frequent small updates
Excellent
Moderate
Poor
Data Encryption
(
Source-04)
Manual
Possible
Manual
DR
Manual Data Replication
SQL Server Data Replication (log shipping, Data  Mirroring, Always ON)
SQL Server Data Replication (log shipping, Always ON)
Backup and Restore
Manual (3rd party tools or OS command can be used)
Part of database backup and restore
Part of database backup and restore
Single point failure/ High availability
Redundant File Servers plus SAN implementation provides no single point failure
SQL Server Clustering plus SAN provides no single point failure
SQL Server Clustering plus SAN provides no single point failure. FileStream should also be on SAN.
TDE (Transparent Data Encryption)
NA
Possible
Not Supported
Database Mirroring
NA
Possible
Not Supported
SNAPSHOT Isolation
NA
Possible
Partially Supported (explanation below)
Authentication
Only Windows Authentication
Supports both SQL Server Authentication and Windows Authentication
Does not support SQL Server Authentication. Only Windows Authentication


2. If we use VARBINARY without filestream enabled, research done by Microsoft indicates – file size <256kb better.="" database="" file="" is="" size="" storage="">1MB file system is better (can be regular file system (NTFS) or FILESTREAM (SQL SERVER). (Source-02)

3. FILESTREAM uses the NT system cache for caching file data. This helps reduce any effect that FILESTREAM data might have on Database Engine performance. The SQL Server buffer pool is not used; therefore, this memory is available for query processing.
(Source-03)

4. FILESTREAM integrates the SQL Server Database Engine with an NTFS file system by storing varbinary(max) binary large object (BLOB) data as files on the file system. Transact-SQL statements can insert, update, query, search, and back up FILESTREAM data. Win32 file system interfaces provide streaming access to the data. (Source-03)

5. Limitation of FileStream of MS SQL Server
  1. TDE (Transparent Data Encryption) is not possible
  2. Database mirroring is not supported for FileStream
  3. SNAPSHOT isolation is not fully supported. If a FILESTREAM filegroup is included in a CREATE DATABASE ON clause, the statement will fail and an error will be raised.
  4. When you are using FILESTREAM, you can create database snapshots of standard (non-FILESTREAM) filegroups. The FILESTREAM filegroups are marked as offline for those database snapshots
  5. For failover clustering, FILESTREAM filegroups must be put on a shared disk. FILESTREAM must be enabled on each node in the cluster that will host the FILESTREAM instance
  6. It’s highly recommended to have separate file group in database to handle FileStream
  7. FileStream supports Windows authentication only 


Sources:
  1. http://msdn.microsoft.com/library/hh461480
  2. http://research.microsoft.com/apps/pubs/default.aspx?id=64525
  3. http://msdn.microsoft.com/en-us/library/gg471497.aspx
  4. http://msdn.microsoft.com/en-us/magazine/dd695918.aspx
  5. http://technet.microsoft.com/en-us/library/bb895334.aspx



Tuesday, May 28, 2013

Java - TSQL - Error - The statement did not return a result set

Problem:
com.microsoft.sqlserver.jdbc.SQLServerException: The statement did not return a result set.

Background:
Stored Procedure is inserting few records in temporary table and at the end returning record set. (See code snippet-01)

Environment:
SQL Server version - MS SQL Server 2008 R2
Java version - 1.7

Solution:
Use 'SET NOCOUNT ON' as very first statement inside stored procedure to stop returning insert/update/delete/select confirmation message. To demonstrate that I have switched output format to text in 'SQL Server Management Studio' (shortcut key is cntl+T). After that SP execution output looking similar as following where first and third lines are the confirmation message for INSERT and second SELECT. When 'SET NOCOUNT ON' is used, output should include only the table.


EXECUTE SPTest;

(3 row(s) affected)
id
-----------
13
14
15

(3 row(s) affected)


Code snippets:

Snippet-01: dummy stored procedure created to test purpose

IF OBJECT_ID('dbo.SPTest', 'P') IS NOT NULL
DROP PROCEDURE dbo.SPTest;
GO
CREATE PROCEDURE dbo.SPTest
AS
BEGIN

select ID from wk_ctr
create table #test(id INT);
INSERT INTO #TEST
select ID from wk_ctr;

select * from #TEST;

END;

Snippet-02: Java class to invoke the Stored Procedure

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class TestTempTableOutput {
public static void main(String[] args) {

Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
System.out.println("before class load2");
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

System.out.println("before connection creation2");

conn = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=dbname","username","password");

System.out.println("Before statement creation2");
stmt = conn.createStatement();
String sql = "EXECUTE SPTest";
rs = stmt.executeQuery(sql);

if(rs.next())
System.out.println("resultset found");
else
System.out.println("resultset not found");

if(rs != null) rs.close();
if(stmt != null) stmt.close();
if(conn != null) conn.close();
} catch (Exception e) {
e.printStackTrace();
try{
if(rs != null) rs.close();
if(stmt != null) stmt.close();
if(conn != null) conn.close();
}catch(Exception ex){}
}
System.out.println("finished");
}
}

Tips:
1. To change SQL Server Management studio output format to text, use shortcut (ctrl+t)
2. To change SQL Server Management studio output format to table, use shortcut (ctrl+d)

Tuesday, April 16, 2013

TSQL - Coding - Dynamic query


Background: sp_executesql is used to execute dynamic query in SQL Server. Below few examples are given to demonstrate the use.

Table structure and data script:

DROP TABLE test;
GO


CREATE TABLE test (group_id INT, name VARCHAR(100));
GO
INSERT INTO test VALUES (1, 'First');
INSERT INTO test VALUES (1, 'Second');
INSERT INTO test VALUES (2, 'Third');
INSERT INTO test VALUES (2, 'Fourth');
INSERT INTO test VALUES (2, 'Fifth');
INSERT INTO test VALUES (3, 'Sixth');
GO

SELECT * FROM test;


Example-01: Use sp_executesql to execute a SELECT query

DECLARE @query NVARCHAR(200);
DECLARE @paramDifinition NVARCHAR(50);
DECLARE @value INT;

SET @query = N'SELECT * FROM wk_be_customer WHERE web_reference_id=@in';
SET @paramDifinition = N'@in INT';
SET @value = 233;

EXECUTE sp_executesql @query, @paramDifinition, @value;

Example-02: Use sp_executesql to execute a UPDATE query


-- Dynamic query - UPDATE
DECLARE @query NVARCHAR(200);
DECLARE @paramDifinition NVARCHAR(50);
DECLARE @value1 INT, @value2 INT;

SET @query = N'UPDATE test SET group_id=@in1 WHERE group_id=@in2';
SET @paramDifinition = N'@in1 INT, @in2 INT';
SET @value1 = 1;
SET @value2=2;

EXECUTE sp_executesql @query, @paramDifinition, @value1, @value2;


Example-03: Use sp_executesql to execute a UPDATE query with IN clause (string concatenation)


DECLARE @query NVARCHAR(200);
DECLARE @paramDifinition NVARCHAR(50);
DECLARE @value1 NVARCHAR(100), @value2 INT;

SET @value1 = '1,2';
SET @query = N'UPDATE test SET group_id=@in1 WHERE group_id IN ('+@value1+')';
SET @paramDifinition = N'@in1 INT';
SET @value2=3;

EXECUTE sp_executesql @query, @paramDifinition, @value2;


Notes:
1. sp_executesql - input parameters have to be NVARCHAR type

Resources:
1. http://msdn.microsoft.com/en-us/library/ms188001.aspx

Thursday, March 28, 2013

MS SQL Server - DBA - DMV - Find out DB/table lock


Environment:
SQL Server 2008 R2 - DMV (Dynamic Management View)


Query to see the locks across database:

SELECT  L.request_session_id AS SPID, 
        DB_NAME(L.resource_database_id) AS DatabaseName,
        O.Name AS LockedObjectName, 
        P.object_id AS LockedObjectId, 
        L.resource_type AS LockedResource, 
        L.request_mode AS LockType,
        L.request_status AS LockStatus,
        ST.text AS SqlStatementText,        
        ES.login_name AS LoginName,
        ES.host_name AS HostName,
        TST.is_user_transaction as IsUserTransaction,
        AT.name as TransactionName,
        CN.auth_scheme as AuthenticationMethod
FROM    sys.dm_tran_locks L
        JOIN sys.partitions P ON P.hobt_id = L.resource_associated_entity_id
        JOIN sys.objects O ON O.object_id = P.object_id
        JOIN sys.dm_exec_sessions ES ON ES.session_id = L.request_session_id
        JOIN sys.dm_tran_session_transactions TST ON ES.session_id = TST.session_id
        JOIN sys.dm_tran_active_transactions AT ON TST.transaction_id = AT.transaction_id
        JOIN sys.dm_exec_connections CN ON CN.session_id = ES.session_id
        CROSS APPLY sys.dm_exec_sql_text(CN.most_recent_sql_handle) AS ST
WHERE   resource_database_id = db_id()
ORDER BY L.request_session_id

Note:
  1. This query will run using selected database - db_id().
  2. sys.dm_tran_locks - system table has two types of columns (resource and request). The resource group describes the resource on which the lock request is being made, and the request group describes the lock request. 
  3. Values in sys.dm_tran_locks.resource_type - KEY, PAGE, DATABASE, FILE, OBJECT etc
  4. Values in sys.dm_tran_locks.request_mode - 
    • NULL = No access is granted to the resource. Serves as a placeholder.
    • Sch-S = Schema stability. Ensures that a schema element, such as a table or index, is not dropped while any session holds a schema stability lock on the schema element.
    • Sch-M = Schema modification. Must be held by any session that wants to change the schema of the specified resource. Ensures that no other sessions are referencing the indicated object
    • S = Shared. The holding session is granted shared access to the resource.
    • U = Update. Indicates an update lock acquired on resources that may eventually be updated. It is used to prevent a common form of deadlock that occurs when multiple sessions lock resources for potential update at a later time.
    • X = Exclusive. The holding session is granted exclusive access to the resource.
    • IS = Intent Shared. Indicates the intention to place S locks on some subordinate resource in the lock hierarchy.
    • IU = Intent Update. Indicates the intention to place U locks on some subordinate resource in the lock hierarchy.
    • IX = Intent Exclusive. Indicates the intention to place X locks on some subordinate resource in the lock hierarchy.
    • SIU = Shared Intent Update. Indicates shared access to a resource with the intent of acquiring update locks on subordinate resources in the lock hierarchy.
    • SIX = Shared Intent Exclusive. Indicates shared access to a resource with the intent of acquiring exclusive locks on subordinate resources in the lock hierarchy.
    • UIX = Update Intent Exclusive. Indicates an update lock hold on a resource with the intent of acquiring exclusive locks on subordinate resources in the lock hierarchy.
    • BU = Bulk Update. Used by bulk operation
    • There are few others about range related
  5. Values in sys.dm_tran_locks.request_status - 
    • GRANT: the lock request was granted
    • WAIT: The request to acquire a particular lock type is waiting.
    • CONVERT: the request was granted earlier with a particular lock status but now is trying to upgrade to another status and is being blocked
Query to find lock on a table:

SELECT REQUEST_MODE, REQUEST_TYPE, REQUEST_SESSION_ID FROM
sys.dm_tran_locks
WHERE RESOURCE_TYPE = 'OBJECT'
AND RESOURCE_ASSOCIATED_ENTITY_ID =(SELECT OBJECT_iD('name_of_the_table'))
ORDER BY request_mode;

Note:
  1. Have to change 'name_of_the_table' to correct table
Kill a open session:
Command - KILL ;

Note: 
  1. sessionid can be found by running above queries.  
  2. Most of the time killing exclusive (X) type request solves table/db lock issue
Resources: 
1. http://social.msdn.microsoft.com/Forums/en-US/sqlgetstarted/thread/cae67b92-1f17-4f97-b68e-cfaba1207253/
2. http://msdn.microsoft.com/en-us/library/ms190345.aspx