Wednesday 25 September 2013

Timeout expired. The timeout period elapsed prior to completion of the operation of the server is not responding.

private DataSet Account_Statement_Schemewise(string ID, string Type, string FromDate, string ToDate)
    {
        System.Collections.Specialized.NameValueCollection nv = new System.Collections.Specialized.NameValueCollection();

        nv.Add("@Id", ID);
        nv.Add("@Type", Type);
        nv.Add("@FromDate", FromDate);
        nv.Add("@ToDate", ToDate);
        DataLayer Obj = new DataLayer
        return Obj .GetDataSet("statement", nv);
    }





 public DataSet GetDataSet(string Stored_Procedure, NameValueCollection nv)
    {
        DataSet ds = new DataSet();
        SqlConnection cn = new SqlConnection(objDBHelper.GetConnectionString());
        SqlCommand cmd = new SqlCommand(Stored_Procedure, cn);

        for (int i = 0; i < nv.Count; i++)
        {
            SqlParameter param;
            if (nv.Get(nv.AllKeys[i]) == null)
                param = new SqlParameter(nv.AllKeys[i], DBNull.Value);
            else
                param = new SqlParameter(nv.AllKeys[i], nv.Get(nv.AllKeys[i]));
            cmd.Parameters.Add(param);
        }
        cmd.CommandTimeout = 999999;
        cmd.CommandType = CommandType.StoredProcedure;
        SqlDataAdapter da = new SqlDataAdapter(cmd);

        try
        {
            cn.Open();
            da.Fill(ds);
        }
        catch (Exception ex)
        {

            da.Dispose();
            cmd.Connection.Close();
            cn.Close();
            throw ex;
        }
        finally
        {
            da.Dispose();
            cmd.Connection.Close();
            cn.Close();
        }
        return ds;
    }

Monday 23 September 2013

How to Dynamically pass columnname in select query?

declare @var varchar(10);
set @var='';
select @var='Column1,column2,column3,column4,column5';
select @var = @var + COLUMN_NAME + ','
        from INFORMATION_SCHEMA.COLUMNS
where TABLE_NAME = ' T_TableName ' and column_name=@var
exec ('select top 10 '+@var+' from T_TableName order by '+ @var+' desc ')

Sunday 22 September 2013

Get difference between 2 dates in javascript and fromdate cannot be greater than todate?

 function ValidateDate()
        {
         var FrDateSelect =document.getElementById('<%=ddlfrDate.ClientID%>').value;
         var ToDateSelect =document.getElementById('<%=ddlToDate.ClientID%>').value;
         var diffDays = (new Date(ToDateSelect) - new Date(FrDateSelect))/ (1000 * 60 * 60 * 24* 30);
         if(new Date(ToDateSelect)<new Date(FrDateSelect))
         {
         alert('From Date Cannot be Greater than To Date');
         return false;
         }  
         else if(diffDays>4)
         {
         alert('select only range of any 3 months');
         return false;
         }  
         else
         {
         return true;
         }
         }

Tuesday 17 September 2013

How to Execute EXE file in ASP.NET

protected void Btn_Execute_Click(object sender, EventArgs e)
    {
        try
        {
            Process myprocess = new Process();
            myprocess.StartInfo.FileName = ExePath;
            myprocess.StartInfo.FileName = @"D:\exefilename.exe";
            myprocess.Start();
            td_Mesg.Visible = true;
        }
        catch(Exception ex)
        {
            Response.Write(ex.Message.ToString());
        }
        finally
        {
            ;
        }
      
    }
    protected void Btn_Stop_Click(object sender, EventArgs e)
    {
        try
        {
            Process[] p = Process.GetProcessesByName("processname");
            for (int i = 0; i < p.Length; i++)
            {
                p[i].Kill();
            }
            if (p.Length > 0)
            {
                td_Mesg.InnerHtml = "EXE stopped successfully ...";
            }
            else
            {
                td_Mesg.InnerHtml = "Currently EXE is not running ...";
            }


        }
        catch (Exception ex)
        {
            td_Mesg.InnerHtml = ex.Message.ToString();
        }
        finally
        {
            ;
        }

    }

Log Errors in ASPX Page

 public static void WriteError(string errorMessage)
    {
        try
        {
            string path = "~/Error/" + DateTime.Today.ToString("dd-MM-yyyy") + ".txt";
            if (!File.Exists(System.Web.HttpContext.Current.Server.MapPath(path)))
            {
                File.Create(System.Web.HttpContext.Current.Server.MapPath(path)).Close();
            }
            using (StreamWriter w = File.AppendText(System.Web.HttpContext.Current.Server.MapPath(path)))
            {
                w.WriteLine("\r\nLog Entry : ");
                w.WriteLine("{0}", DateTime.Now.ToString(CultureInfo.InvariantCulture));
                string err = "Error in: " + System.Web.HttpContext.Current.Request.Url.ToString() +
                              ". Error Message:" + errorMessage;
                w.WriteLine(err);
                w.WriteLine("__________________________");
                w.Flush();
                w.Close();
            }
        }
        catch (Exception ex)
        {
            WriteError(ex.Message);
        }

    }

Extending the ASP.NET error page (show me the SQL edition)

ASP.NET has the infamous yellow screen of death. Rumor is that it was written by “The Gu” himself. It is an incredibly useful page that allows you to quickly and easily determine why stuff went wrong, while debugging your code. You get a stack trace, including the line of code and context for your error.
There is a slight snag though. When diagnosing SQL errors this page is lacking. Even though you are provided with the exception SQL Server returned, you do not get the SQL that executed nor do you get the parameters. Often I found myself setting break points and attaching, just to get at the SQL. This is very wasteful.
So I thought … why not extend the error page. Turns out this is fairly tricky.
There are two very big problems. Firstly, DbException and derived classes do not have any idea what the CommandText is. Secondly, extending the yellow screen of death is totally undocumented.
Nonetheless, I care not for such limitations. I wanted this:
rich error

Step 1 – storing and formatting the SQL statement

The custom DbConnection we use with MiniProfiler makes tracking the failed SQL simple.
First, we extend the ProfiledDbConnection:
public sealed class RichErrorDbConnection : ProfiledDbConnection
{
#if DEBUG
        DbConnection connection;
        MiniProfiler profiler;
#endif

        public RichErrorDbConnection(DbConnection connection, MiniProfiler profiler)
            : base(connection, profiler)
        {
#if DEBUG
            this.connection = connection;
            this.profiler = profiler;
#endif
        }


#if DEBUG
        protected override DbCommand CreateDbCommand()
        {
            return new RichErrorCommand(connection.CreateCommand(), connection, profiler);
        }
#endif
} 
Next we implement a class that intercepts the exceptions and logs the SQL.
public class RichErrorCommand : ProfiledDbCommand
{ 
    public RichErrorCommand(DbCommand cmd, DbConnection conn, IDbProfiler profiler) : base(cmd, conn, profiler)
    {
    }

    void LogCommandAsError(Exception e, ExecuteType type)
    {
        var formatter = new MvcMiniProfiler.SqlFormatters.SqlServerFormatter();
        SqlTiming timing = new SqlTiming(this, type, null);
        e.Data["SQL"] = formatter.FormatSql(timing);
    }

    public override int ExecuteNonQuery()
    {
        try
        {
            return base.ExecuteNonQuery();
        }
        catch (DbException e)
        {
            LogCommandAsError(e, ExecuteType.NonQuery);
            throw;
        }
    }

    protected override DbDataReader ExecuteDbDataReader(CommandBehavior behavior)
    {
        try
        {
            return base.ExecuteDbDataReader(behavior);
        }
        catch (DbException e)
        {
            LogCommandAsError(e, ExecuteType.Reader);
            throw;
        }
    }

    public override object ExecuteScalar()
    {
        try
        {
            return base.ExecuteScalar();
        }
        catch (DbException e)
        {
            LogCommandAsError(e, ExecuteType.Scalar);
            throw;
        }
    }
}
During debug we now make sure we use RichErrorDbConnection as our db connection.

Step 2 – extending the error page

This was fairly tricky to discover, it lives in global.asax.cs:
protected void Application_Error(object sender, EventArgs e)
{
#if DEBUG 
    var lastError = Server.GetLastError();
    string sql = null;

    try
    {
        sql = lastError.Data["SQL"] as string;
    }
    catch
    { 
        // skip it
    }

    if (sql == null) return;

    var ex = new HttpUnhandledException("An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.", lastError);

    Server.ClearError();

    var html = ex.GetHtmlErrorMessage();
    var traceNode = "<b>Stack Trace:</b>";
    html = html.Replace(traceNode, @"<b>Sql:</b><br><br>
    <table width='100%' bgcolor='#ffffccc'>
    <tbody><tr><td><code><pre>" + sql + @"</pre></code></td></tr></tbody>
    </table><br>" + traceNode);

    HttpContext.Current.Response.Write(html);
    HttpContext.Current.Response.StatusCode = 500;
    HttpContext.Current.Response.Status = "Internal Server Error";
    HttpContext.Current.Response.End();

#endif
}
The trick here is that we use a string replace to yank in the new chunk of html.

I hope that future releases of the platform make both of the hacks easier to implement. It would be awesome if MVC4 shipped a template error page you can just edit. It would be awesome if the base ado.net interfaces provided a means of interception without needing a full re-implementation.

Reference : http://samsaffron.com/archive/2011/09/08/Extending+the+ASP.NET+error+page+show+me+the+SQL+edition

Friday 13 September 2013

Login Check using HTML and JavaScript

<html>
<head>
<title></title>
 <script type="text/javascript">

 function validate()
 {
 var username=document.getElementById('txtname').value;
 var password=document.getElementById('txtpass').value;
 if(username=="abc" && password=="abc")
 {
 window.location="http://www.google.com";
 }
 else
 {
  alert("Login Failed");
  document.getElementById("txtpass").value="";
  document.getElementById("txtpass").focus();
 }
}
 </script> 
   
   
</head>
<body>

    <div>
        <table>
            <tr>
              
                <td>
                UserName
                </td>
                <td>
                <input type="text" name="txtname" size="20" id="txtname"/>
                </td>
            </tr>
            <tr>
                <td>
                    Password
                </td>
                <td>
                    <input type="text" name="txtpass" size="20" id="txtpass" />
                </td>
            </tr>
             <tr>
                <td>
                    &nbsp;
                </td>
                <td>
                <input type="button" value="Submit" onclick="validate()" id="btnsubmit" />
               
                </td>
            </tr>
        </table>
    </div>

</body>
</html>

Friday 6 September 2013

What is the difference between varchar and nvarchar?



An nvarchar column can store any Unicode data. A varchar column is restricted to an 8-bit codepage. Some people think that varchar should be used because it takes up less space. I believe this is not the correct answer. Codepage incompatabilities are a pain, and Unicode is the cure for codepage problems. With cheap disk and memory nowadays, there is really no reason to waste time mucking around with code pages anymore.
All modern operating systems and development platforms use Unicode internally. By using nvarcharrather than varchar, you can avoid doing encoding conversions every time you read from or write to the database. Conversions take time, and are prone to errors. And recovery from conversion errors is a non-trivial problem.
If you are interfacing with an application that uses only ASCII, I would still recommend using Unicode in the database. The OS and database collation algorithms will work better with Unicode. Unicode avoids conversion problems when interfacing with other systems. And you will be preparing for the future. And you can always validate that your data is restricted to 7-bit ASCII for whatever legacy system you're having to maintain, even while enjoying some of the benefits of full Unicode storage.

Understanding the SQL Server NOLOCK hint

Problem

I see the use of the NOLOCK hint in existing code for my stored procedures and I am not exactly sure if this is helpful or not. It seems like this has been a practice that was put in place and now is throughout all of the code wherever there are SELECT statements. Can you explain the what NOLOCK does and whether this is a good practice or not?

Solution

It seems that in some SQL Server shops the use of the NOLOCK (aka READUNCOMMITED) hint is used throughout the application. In this tip we take a closer look at how this works and what the issues maybe when using NOLOCK.

Example

Let's walk through some simple examples to see how this works. (These queries are run against the AdventureWorks database.)
Here is a query that returns all of the data from the Person.Contact table. If I run this query I can see there is only one record that has a Suffix value for ContactID = 12.
SELECT * FROM Person.Contact WHERE ContactID < 20
use of the nolock(aka readuncommited) hint
Let's say another user runs the below query in a transaction. The query completes and updates the records, but it is not yet committed to the database so the records are locked.
-- run in query window 1
BEGIN TRAN
UPDATE Person.Contact SET Suffix = 'B' WHERE ContactID < 20
-- ROLLBACK or COMMIT
If I run the same query from above again you will notice that it never completes, because the UPDATE has not yet been committed.
-- run in query window 2
SELECT * FROM Person.Contact WHERE ContactID < 20
If I run sp_who2 I can see that the SELECT statement is being blocked. I will need to either cancel this query or COMMIT or ROLLBACK the query in window one for this to complete. For this example I am going to cancel the SELECT query.
commit or rollback query
To get around the locked records, I can use the NOLOCK hint as shown below and the query will complete even though the query in window 1 is still running and has not been committed or rolled back.
-- run in query window 2
SELECT * FROM Person.Contact WITH (NOLOCK) WHERE ContactID < 20
If you notice below the Suffix column now has "B" for all records. This is because the UPDATE in window 1 updated these records. Even though that transaction has not been committed, since we are using the NOLOCK hint SQL Server ignores the locks and returns the data. If the UPDATE is rolled back the data will revert back to what it looked like before, so this is considered a Dirty Read because this data may or may not exist depending on the final outcome in query window 1.
using the nolock hint sql server ignores the locks
If I rollback the UPDATE using the ROLLBACK command and rerun the SELECT query we can see the Suffix is back to what it looked like before.
-- run in query window 1
ROLLBACK

-- run in query window 2
SELECT * FROM Person.Contact WITH (NOLOCK) WHERE ContactID < 20
-- or
SELECT * FROM Person.Contact WHERE ContactID < 20
using the rollback command
So the issue with using the NOLOCK hint is that there is the possibility of reading data that has been changed, but not yet committed to the database. If you are running reports and do not care if the data might be off then this is not an issue, but if you are creating transactions where the data needs to be in a consistent state you can see how the NOLOCK hint could return false data.

Locks

So what kind of locking is used when the NOLOCK hint is used.
If we run our SELECT without NOLOCK we can see the locks that are taken if we use sp_lock. (To get the lock information I ran sp_lock in another query window while this was running.)
SELECT * FROM Person.Contact WHERE ContactID < 20
we can see the locks that are taken if we use sp_lock
If we do the same for our SELECT with the NOLOCK we can see these locks.
SELECT * FROM Person.Contact WITH (NOLOCK) WHERE ContactID < 20
sql server still creates a lock to make sure the data is consistent
The differences are that there is a "S" shared access lock that is put on the page (PAG) that we are reading for the first 19 rows of data in the table when we don't use NOLOCK. Also, we are getting a Sch-S lock versus an IS lock for the table (TAB).
So another thing to point out is that even when you just SELECT data SQL Server still creates a lock to make sure the data is consistent.
These are the lock types and the lock modes that are used for the above two queries.

Lock Types

  • MD - metadata lock
  • DB - database lock
  • TAB - table lock
  • PAG - page lock

Mode

  • S - Shared access
  • Sch-S - Schema stability makes sure the schema is not changed while object is in use
  • IS - Intent shared indicates intention to use S locks

READUNCOMMITED

The NOLOCK hint is the same as the READUNCOMMITED hint and can be used as follows with the same results.
SELECT * FROM Person.Contact WITH (READUNCOMMITTED)

SELECT statements only

The NOLOCK and READUNCOMMITED hints are only allowed with SELECT statements. If we try to use this for an UPDATE, DELETE or INSERT we will get an error.
UPDATE Person.Contact with (NOLOCK) SET Suffix = 'B' WHERE ContactID < 20

Msg 1065, Level 15, State 1, Line 15
The NOLOCK and READUNCOMMITTED lock hints are not allowed for target tables of INSERT, UPDATE, DELETE or MERGE statements.

Schema Change Blocking

Since a NOLOCK hint needs to get a Sch-S (schema stability) lock, a SELECT using NOLOCK could still be blocked if a table is being altered and not committed. Here is an example.
-- run in query window 1
BEGIN TRAN
ALTER TABLE Person.Contact ADD column_b VARCHAR(20) NULL ;
If we try to run our SELECT statement it will be blocked until the above is committed or rolled back.
-- run in query window 2
SELECT * FROM Person.Contact WITH (NOLOCK) WHERE ContactID < 20

Issues

We mentioned above how you can get dirty reads using the NOLOCK hint. These are also other terms you may encounter for this hint.
  • Dirty Reads - this occurs when updates are done, so the data you select could be different.
  • Nonrepeatable Reads - this occurs when you need to read the data more than once and the data changes during that process
  • Phantom Reads - occurs where data is inserted or deleted and the transaction is rolled back. So for the insert you will get more records and for the delete you will get less records.
To learn more about these issues read this article: http://msdn.microsoft.com/en-us/library/ms190805.aspx

Isolation Level

You can also set the Isolation Level for all queries instead of using the NOLOCK or READUNCOMMITTED hint. The isolation level will apply the READUNCOMMITTED to all SELECT statements that are performed from when this is turned on until it is turned off.
In the example below, the two SELECT statements will use the READUNCOMMITED or NOLOCK hint and the UPDATE will still function as normal. This way you can set a whole batch of statements instead of modifying each query.
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED; -- turn it on

SELECT * FROM Person.Contact WHERE ContactID < 20

UPDATE Person.Contact SET Suffix = 'B' WHERE ContactID = 1

SELECT * FROM Person.Contact WHERE ContactID < 20

SET TRANSACTION ISOLATION LEVEL READ COMMITTED; -- turn it off

Next Steps

Using NOLOCK and READPAST table hints in SQL Server

Table locking hints provide developers much tighter control of their transactions. Look at the benefits and disadvantages of using the NOLOCK and READPAST table hints in SQL Server.
When data in a database is read or modified, the database engine uses special types of controls, called locks, to maintain integrity in the database. Locks basically work by making sure database records involved in a transaction cannot be modified by other transactions until the first transaction has committed, ensuring database consistency. When designing database applications, you should keep in mind the different types of locks that will be issued, and the different levels of isolation your transactions will occur. Typically, the SQL Server defaults work fine for what you are trying to accomplish. However, there will be times when it is advantageous to manually make hints to how locks are issued on your tables in your SQL statements.
This article focuses on two table hints: NOLOCK and READPAST. I'll set up a table to use for our example queries. Execute the script in Listing A to create the SalesHistory table and populate the table with data.

NOLOCK

This table hint, also known as READUNCOMMITTED, is applicable to SELECT statements only. NOLOCK indicates that no shared locks are issued against the table that would prohibit other transactions from modifying the data in the table.
The benefit of the statement is that it allows you to keep the database engine from issuing locks against the tables in your queries; this increases concurrency and performance because the database engine does not have to maintain the shared locks involved. The downside is that, because the statement does not issue any locks against the tables being read, some "dirty," uncommitted data could potentially be read. A "dirty" read is one in which the data being read is involved in a transaction from another connection. If that transaction rolls back its work, the data read from the connection using NOLOCK will have read uncommitted data. This type of read makes processing inconsistent and can lead to problems. The trick is being able to know when you should use NOLOCK.
As a side note, NOLOCK queries also run the risk of reading "phantom" data, or data rows that are available in one database transaction read but can be rolled back in another. (I will take a closer look at this side effect in part two of this article series.)
The following example shows how NOLOCK works and how dirty reads can occur. In the script below, I begin a transaction and insert a record in the SalesHistory table.
BEGIN TRANSACTION
      INSERT INTO SalesHistory
      (Product, SaleDate, SalePrice)          
      VALUES            
      ('PoolTable', GETDATE(), 500)                   
The transaction is still open, which means that the record that was inserted into the table still has locks issued against it. In a new query window, run the following script, which uses the NOLOCK table hint in returning the number of records in the SalesHistory table.
SELECT COUNT(*) FROM SalesHistory WITH(NOLOCK)
The number of records returned is 301. Since the transaction that entered the record into the SalesHistory table has not been committed, I can undo it. I'll roll back the transaction by issuing the following statement:
ROLLBACK TRANSACTION
This statement removes the record from the SalesHistory table that I previously inserted. Now I run the same SELECT statement that I ran earlier:
SELECT COUNT(*) FROM SalesHistory WITH(NOLOCK)
This time the record count returned is 300. My first query read a record that was not yet committed -- this is a dirty read.

READPAST

This is a much less commonly used table hint than NOLOCK. This hint specifies that the database engine not consider any locked rows or data pages when returning results.
The advantage of this table hint is that, like NOLOCK, blocking does not occur when issuing queries. In addition, dirty reads are not present in READPAST because the hint will not return locked records. The downside of the statement is that, because records are not returned that are locked, it is very difficult to determine if your result set, or modification statement, includes all of the necessary rows. You may need to include some logic in your application to ensure that all of the necessary rows are eventually included.
The READPAST table hint example is very similar to the NOLOCK table hint example. I'll begin a transaction and update one record in the SalesHistory table.
BEGIN TRANSACTION
      UPDATE TOP(1) SalesHistory
      SET SalePrice = SalePrice + 1
Because I do not commit or roll back the transaction, the locks that were placed on the record that I updated are still in effect. In a new query editor window, run the following script, which uses READPAST on the SalesHistory table to count the number of records in the table.
SELECT COUNT(*)

FROM SalesHistory WITH(READPAST)
My SalesHistory table originally had 300 records in it. The UPDATE statement is currently locking one record in the table. The script above that uses READPAST returns 299 records, which means that because the record I am updating is locked, it is ignored by the READPAST hint.

WITH (NOLOCK) example

Introduction

I want to show the use of With (NoLock) hit with a simple example but before that let's brush up following term.
Lock it allows different type of resource to be lock by the transaction.
When user accessing data, data get locks so that other user cannot modify or delete data that someone is reading.
A transaction is unit of work submitted as hole to database for processing.
Dirty Read is a process of reading database record without locking the record being read.
Stand the risk of reading an uncommitted row that is subsequently rolled back. Resulting in reading of local copy of record that is not consistent with what is stored in database.
Non repeatable read is a situation where a session finds itself in when it perform multiple read.
It is possible to perform the query in the same transaction more than one and show different result.
Phantom row is rows that douse not appear in the initial read, but appear when same data is read again during the same transaction.
This occur when user insert a record while transaction is underway.
Shared Lock(s) is read lock it is occur when SQL server perform select statement or any other statement to read the data tell to read but do not modify the data.
When one user is reading the data he/she issue read lock so that other user do not modify data.
Exclusive Lock (x) are generally use during modification activity use to lock data being modified by one transaction.it prevent modification by another concurrent transaction.
Update Lock (u) update lock a mix of shared and exclusive lock.
Update Lock is kind of Exclusive Lock except it can be placed on the row which already has Shared Lock on it. Update Lock reads the data of row which has Shared Lock, as soon as Update Lock is ready to change the data it converts itself to Exclusive Lock.
WITH (NOLOCK) hit
Do not issue shared locks and do not honor exclusive locks. When this option is in effect, it is possible to read an uncommitted transaction or a set of pages that are rolled back in the middle of a read. Dirty reads are possible. Only applies to the SELECT statement.

Background 

In the following example we are denoting two seperate user by opening two sperate query window in SQL Server. I am using Northwind database on both the windows. So sotry is like this
User one update table saying that Dairy Products are Chees and Paneer but he did not commit data.
User one weight for an approval.
User two fire Select qury same time but qury run infinite loop as select qury issue share lock that is not granted as User one is updating data.
Another user fire Select qury same time WITH (NOLOCK) hit and qury run to show uncommitted data as Diry product "Chees and Paneer".
As our user one approval is rejected and he roll back his update to Dairy product to Chees only.
Oh the user with nolock hit is still considering that Diry product contin the Paneer.
But he still avoid the situation of being dead lock like user one.

Using the code

Let's open query window one and run the update query as mention bellow.
--Query window 1
USE Northwind
SELECT * FROM Categories

BEGIN TRANSACTION
 
UPDATE Categories SET Description='Cheese and Paneer' 
WHERE CategoryName='Dairy Products' 
SELECT * FROM Categories 

Open query window two and fire the same SELECT query.
--Qury window 2
USE Northwind 
SELECT * FROM Categories 
I run the same query from above again and i have notice that it never completes, because the UPDATE has not yet been committed.
Open query window third and fire the same SELECT query WITH (NOLOCK) hit.
--Qury window 3 
USE Northwind 
SELECT * FROM Categories WITH (NOLOCK) 

--Let me rollback the query in Window 1. 
ROLLBACK 
SELECT * FROM Categories  
But our window  3 user is still considering that  Diary Products are Cheese and Paneer reading uncommitted data that is rolled back after time.
And our window 2 user is fall in to dead lock condition.
We can find the lock issue in each window using sp_lock.
If we run our SELECT without NOLOCK we can see the locks that are taken if we use sp_lock.
For window 2 while our query is in dead lock we can veryfy lock on the page by firing sp_lock on separate window.
You can find that there is share lock issue when you run the select query with out (NOLOCK) and there is NO Share lock issue when you run the qury with (NOLOCK). Hence when you perform update in that is yet to commit exclusive lock is issue.
Where (NOLOCK) dous not honour exclusive lock.


More Links:  http://sqlserverplanet.com/tsql/using-with-nolock

C# LINQ Joins With SQL

There are  Different Types of SQL Joins  which are used to query data from more than one database tables. In this article, you will learn a...