SQL Server (Table might be locked by some process) - how to release - sql-server

I am using SQL Server 2012. I am bot able to select rows from a table "Prime.ProductMaster".
When I write query like Select * from Prime.ProductMaster then it continue executing forever.
When I run the same query with Nolock. i.e Select * from Prime.ProductMaster WITH(NOLOCK) it executes.
I have investigated on this and found the problem that after row No 2778 the problem exists. I think table might be locked by some other process.
Could anyone please help me how to overcome from this issue. I cant restart sql server as it is shared by many people.

You can right click on our SQL instance name and view Activity Monitor, alternately, click the icon on the far right of your screen shot.
Underneath Resource Waits you should see a row that indicates any Lock that might be held. If this reads 0 there are no locks, otherwise some other process is creating and holding a Lock on the table or rows.
Underneath Processes, you should be able to see active connections, which you can filter by Database and in your case, perhaps Wait Type, to identify the process that is holding the Lock. Whilst this may indicate the cause and you could simply right click and kill process, depending on the application scenario I would use this information to investigate the issue/code that is causing this Lock.
If it's not clear, you may need to profile your database using SQL Server Profiler to track the root cause of the Lock. I would suggest setting up the profiler to check for Locks and possible Deadlocks to filter out "noise" from the trace.
If you need info on how to profile Locks, take a look at this video.

Related

Databases are not getting displayed in SSMS

I'm using SQL Server 2012 and I'm stuck with a strange problem.
I tried to restore a database snapshot to a database. Usually it doesn't take much time to restore, but now it took 5 minutes and is still restoring, so I stopped query execution. It was trying to stop the query execution for more that 5 minutes, so i closed SSMS using task manager.
Then I tried to kill the restore process using KILL.
Now I am able to can connect to that server, but the list of databases is not opening. I mean: whoever is connected to this server, they are not able to get the databases. When I checked the sysprocesses table, it is showing lastwaittype as LCK_M_S.
None of my users can see databases. Looks like I kind of messed up. I cannot restart SQL Server as others are connected to the server.
How do I solve this? Please help.
EDIT:
i tried this approach and when i checked with
select db_name(dbid), * from sysprocesses where blocked <> 0
i got two records,
do you think because of these two rest of the process are getting locked up.
I'm guessing there still is some hidden lock on the sysdatabases table in the master database. This could very well be caused by the KILL of the restore command.
The article here might help you:
http://ellisweb.net/2012/02/clearing-out-a-mysterious-table-lock-lck_m_s-in-sql-server-2008/
It basically advises you to identify where the hidden lock is coming from, and then issuing a KILL on that process ID.
Try restarting the instance. Can't hurt if your users can't see any of the databases anyway.

MS Access holds locks on table rows indefinitely

We're using MS Access as the GUI for one of our systems, but we've run into an issue where Access is holding locks on the underlying tables or rows, which prevents SQL server from running any update queries on this data. This is problematic because while our Access frontend only requires read only access to this data, we have systems in place that are refreshing the data at regular intervals. These refresh operations fail (or are delayed indefinitely) due to Access already holding locks on the data.
This problem is illustrated by opening the Access frontend and using the sys.dm_tran_locks DMV to show locks on the data. The steps I take to reproduce the problem are:
Open the Access frontend. This shows a scrollable form with several thousand records
Use SQL server DMVs to show locks on the data. This shows 5 "object" type locks with request mode of "IS" (Intent shared). Using sys.dm_exec_requests shows the command status as "suspended" and the wait type as "ASYNC_NETWORK_IO". These locks are held as long as the user has the Access frontend open, and prevent any update/delete/truncate operations on the tables involved. Now if the user scrolls to the end of the record set in Access, the locks are released!
The second issue occurs when the user clicks through to show a single record in the frontend. When a single record is displayed onscreen, the SQL server DMVs show these locks: 3x object, 1x key, 1x page. The key is a shared lock, others are intent shared. Again, command status is suspended and wait type is ASYNC_NETWORK_IO. And these locks are held as long as the user is viewing the record
We need to stop access from holding these locks on an indefinite basis. Unfortunately MS Access is not part of my skill set so I don't know what needs to be done to fix this.
I didn't solve this problem, but a colleague did. What was done is that instead of creating linked tables to SQL Server tables he created linked tables to views. The views looked like this:
CREATE VIEW dbo.acc_tblMyTable
AS
SELECT * FROM tblMyTable WITH (NOLOCK)
No locking, and as a bonus Access treated the data as read-only.
Make sure you understand what can happen when you use NOLOCK, however.
Unfortunately MS Access is not part of my skill set so I don't know what needs to be done to fix this.
Get rid of Access :)
Been developing applications that use SQL Server as the backend for years mostly .NET. Never ran into the locking (blocking) issues you are discussing. And a properly designed database should be using SQL Servers' default row level locking on update.
It is Access that is the issue. Since once upon a time it had an internal database that it had full control of it continues to think that is what is has and the behavior is what it thinks is correct. Effectively it has end run the SQL Server to do what it thinks is correct. Not really a good thing since Access is a file based product and a less than production ready one at that. Good for phone books or recipes and that is about all. Doesn't scale either.

Is there a way to prevent from deadlocks (and what happens is one occurs and one is victimized)

I've tried to read an article on locks and deadlocks, and it just doesn't land, al the different kind of locks.
We're running 2 different processes which try to edit records in the same table.
The first process reads the new data and sends it to an external party and updates the status accordingly, the other one receives the receiveresults form the external party and updates the status accordingly.
Now we more and more get deadlocks (in which case one of the two is the victom and gets aborted). So far so good because you can anticipate on that, and try to rerun the statement, but then allways the same deadlock occurs.
So that's my first question: why does the same deadlock allways reoccur?
And second, is there a way to tell the dbms not to try and get an exclusive lock for a record (we update single records via a stored procedure) when another process is already reading and updating it, but 'wait at the side' till the other process is ready?
Or is that a much too simple thing to say about a deadlock?
and may be third, is there a way to ask LINQ to SQL which locks were causing the problem, so i get a little more insight of which parts of the process are causing the problem.
SQL Profiler is the best tool I've used to start trying to solve deadlock problems in SQL Server.
Start a trace:
On the Events Selection tab:
Uncheck all of the preselected events.
Check "Show all events".
Expand "Locks".
Check "Deadlock graph", "Lock:Deadlock", and "Lock Deadlock Chain".
Run the trace and capture the deadlock events.
View the deadlock events in SQL Profiler. The deadlock display is pretty good. You may still need to look at the raw XML to get additional details.
Using what you find from this first pass, may give you ideas on what to change, or suggest other events to trace in SQL Profiler.
As #Darryl Peterson indicates, SQL Profiler is a good tool to capture deadlock information. If you don't know when the deadlock will occur, you can set a SQL Server trace flag to capture the data.
DBCC TRACEON (1204)
When a deadlock occurs, information about the deadlock will be written to the SQL Server error log.
There are a number of ways to get a deadlock. Your first question "why does the same deadlock always occur" is probably a good sign. If the deadlock is repeatable, then you can catch it and fix it.
Regarding your second question, SQL Server is probably already telling one process to wait while the other completes. However, you can't avoid a deadlock by waiting. A deadlock is a situation where a process is trying to use a resource that is held by another process. But the other process is waiting for a resource that the first process is holding. Neither process will release a resource until it completes its work. Note that this is a simple explanation and there can be more complex deadlock conditions. The point is that processes in the deadlock will never be able to complete.
Once you learn more about the processes involved in the deadlock, you should be able to take steps to avoid it.

Can I be a deadlock victim if I'm not executing a query within a transaction?

Lets say I open a transaction and run update queries.
BEGIN TRANSACTION
UPDATE x SET y = z WHERE w = v
The query returns successfully and the transaction stays open deliberately for a period of time before I decide to commit.
While I'm sitting on the transaction is it ever possible the MSSQL deadlock machinary would be able to preempt my open transaction that is not actually executing anything to either clear a deadlock or free resources as system memory/resource limits are reached?
I know about SET DEADLOCK_PRIORITY and have read the MSDN articles on the topic of deadlocks. Logically since I'm not actively seeking to stake claim on any additional resources I can't imagine a scenario that would trigger a sane deadlock avoidance algorithm.
Does anyone know for sure if its possible that simply holding any locks can make me a valid target? Similarly could any low resource condition trigger the killing of my SPID?
NO
For a deadlock to occur all the participants in the deadlock chain must be waiting for a resource (a lock). If your connection is idle it means it doesn't execute a request, which implies it cannot be waiting.
As for other conditions that can kill your session I can think of at least three:
administrative operations that use WITH ROLLBACK_IMMEDIATE
a mirroring failover
intentional KILL <yourspid>, perhaps as a joke by your friendly DBA
To answer your question: you can be a deadlock victim if you're not executing a query in a transaction.
It's counter-intuitive, but you can be a deadlock victim by running a SELECT statement.
It can happen if you're running a query that uses an index:
you scan indexes looking for matching rows
other process starts updating data pages
you now want to fetch data from data pages from matching rows
other process holding locks on data pages
you wait for data page locks to release
other process finished updating data pages, wants to update indexes
you are holding read locks on indexes
other process waits for index locks to release
DEADLOCK
So, strictly speaking, you can be a deadlock victim, when you're not executing a query in a transaction. The other guy wasn't executing his UPDATE statement in a transaction either.
Nobody's explicitly using a transaction, yet there's a deadlock.
Possible problems:
SQL Server only has a finite number of locks. It is possible to run out of locks.
Other resources are finite (e.g. memory, tempdb). Holding on to these resources could cause those resources to run out.
Transaction logs - the logical transaction logs cannot be freed for re-use if a transaction is open. The result could be a log that fills up. This problem could stop your process because it would halt the entire instance.
To consider:
CASCADE: DELETE may only have one table in the command, but the a CASCADE relationship may touch other tables.
Triggers: Triggers on the modified table may affect other tables.
DELETE and UPDATE commands may use the FROM clause which touch other tables. I've never seen this, but I would not rule it out.
Transactions may time out, is that what is happening.
As you have at least 1 (or more) update locks taken out and make be some read and table scan locks, you may be killed to help free up deadlocks created by other transactions. The deadlock recovery code in SQL Server is unlikely to be totally bug free and it is not normal to keep a transaction open for a long time on SQL Server. However I would not expect that to happen often.
Some system when they detach deadlock type problem, just start killing “long lived” transactions that have not done match work so as to free up locks. Just because you are not part of the deadlock loop, does not stop the system picking on you.
To understand what is going on in your case, you will have to use the Sql Server Profiler to collect all the locking and deadlock related events, as well as event about aborted connection and transactions etc. Good lack this will time some time and a good level of understanding of the profiler events you are looking at...
The detail of this sort of things are different between database vendors and versions of their database. However as it is considered bad design by most database vendors to have a transaction open for a long time, doing so tends to lead to problems and hit code paths that have not had the most testing effort.
Just because you're not in a transaction doesn't mean you're not holding locks.

OpenQuery to DB2/AS400 from SQL Server 2000 causing locks

Every morning we have a process that issues numerous queries (~10000) to DB2 on an AS400/iSeries/i6 (whatever IBM calls it nowadays), in the last 2 months, the operators have been complaining that our query locks a couple of files preventing them from completing their nightly processing. The queries are very simplisitic, e.g
Select [FieldName] from OpenQuery('<LinkedServerName>', 'Select [FieldName] from [LibraryName].[FieldName] where [SomeField]=[SomeParameter]')
I am not an expert on the iSeries side of the house and was wondering if anyone had any insight on lock escalation from an AS400/Db2 perspective. The ID that is causing the lock has been confirmed to be the ID we registered our linked server as and we know its most likely us because the [Library] and [FileName] are consistent with the query we are issuing.
This has just started happening recently. Is it possible that our select statements which are causing the AS400 to escalate locks? The problem is they are not being released without manual intervention.
Try adding "FOR READ ONLY" to the query then it won't lock records as you retrieve them.
Writes to the files on the AS/400 side from an RPG/COBOL/JPL job program will cause a file lock (by default I think). The job will be unable to get this lock when you are reading. The solution we used was ... don't read the files when jobs are running. We created a big schedule sheet in excel and put all the sql servers' and as/400's jobs on it in times slots w/ color coding for importance and server. That way no conflicts or out of date extract files either.
You might have Commitment Control causing a lock for a Repeatable Read. Check the SQL Server ODBC connection associated with <linkedServerName> to change the commitment control.

Resources