Entity Framework / SQL Server database locks - sql-server

I am having trouble to understand what locks my SQL Server database. I am accessing data from a SQL Server database via Entity Framework. While that web application is running, I am also checking data with SQL Server Management Studio.
Apparently, when I am trying to read different tables with right click "Select TOP n rows", I get a message
Failed to retrieve data - Lock timeout period exceeded Error 1222).
This doesn't happen when I read the data manually via Select * from ... statement or at least I haven't noticed it yet. Is there any difference between those 2 approaches?
And more important how can I figure out what locks my database? I tried to do research but still not quite specifically understanding what to do. I tried using
DBCC opentran and than
exec sp_who2 SPID
exec sp_lock SPID
which tells me there is an active transaction from Entity Framework but not which one exactly. I am using a few transactions in my application. But those are in my opinion on other tables than I am trying to access via Management Studio. Are those transactions locking up the whole database?
Appreciate any help.

Try to use a great stored procedure who_isActive written by Adam Machanic:
EXEC sp_WhoIsActive;
In addition, this stored procedure shows an executable sql text.
The stored procedure can be downloaded here.
e.g. query with session_id = 75 is waiting of query with session_id = 90:
This is a reason of your blocking.
sp_who2 is great procedure too. E.g.:
Then you should decide whether this process should be killed:
KILL YourNumberOfSessionID

Related

SQL Server SPIDS go into a sleeping state and never recover

I have a long running stored procedure that is executed from IIS. On average this stored procedure takes between two and five minutes to complete because it is searching through a large dataset. (although it has take around 20 minutes in some cases)
Most of the time the stored procedure works fine but every now and then the SPIDS go into a sleeping state and never recover. The only solution I have found is to restart the SQL Server and re-run the stored procedure
The are no table inserts in the proc (only table variable inserts), and the other statements are selects on a large table.
I'm stuck for where to start debugging this issue. Any hints one what it might be or suggestions on tools that would help me find the issue would be most helpful
EDIT: More info added:
The actual issue is the proc doesn't return the resultset. My first thought was to look at the spids, they were sleeping but the cputime was still increasing
It's a .Net app so .Net Core 3.1 with ASP.NET Core and a Blazor UI. The libary used for db connection is System.data.SqlClient I believe System.data.SqlClient uses it's own custom driver. Calling code below:
The stored procedure doesn't return multiple result sets, however obviously different instances of the proc run at the same time.
No limits to connection pooling in IIS
#RichardWatts when you say " re-run the stored procedure" you mean that the same stored proc with the same parameter and data works once you restart SQL Server ?
If so look over your loc (sp_loc} inside your table probably another process loc some data and doesnt release it properly, specialy if you have transaction accessing the same tables.
What is your your isolation level on your connexion ? If you can, try to change it to READ UNCOMMITTED to see if that solve your problem.
as an alternate you can also add a WITH (NOLOCK) or (READUNCOMMITTED) to your sql command.
Know that you will need to hold query with a read uncommited or nolock if you have some modification on the structure of your table or index re construction for example or they will in turn block its execution
Nevertheless be cautious this solution depend on your environment, specially if your tables gots lots of update, delete, insert,... this kind of isolation can lead to a Dirty read and doesnt adress the root cause of your problem wich I would bet is uncomited transaction (good article that explain it)
Make also a DBCC CHECKTABLE just to be sure on this side

How does SQL deal with a long running query via Linked Server if there’s a PC reboot?

I have a SQL Server database and have a linked server connection to an Oracle DB.
I had the following query running on my SQL Server:
INSERT INTO dbo.my_table_on_sql_server
SELECT *
FROM OPENQUERY (linkedservername, ‘SELECT * FROM target_table’)
The target_table has 50 million rows and I'm aware the query takes time to execute but has successfully completed before.
This time though, my PC had an automatic restart in the middle of the query. SSMS 2017 automatically reopened as soon as the PC fired back up, but I could not longer see the query running. my_table_on_sql_server has no data.
I'd like to understand what happens in SQL Server in the event of such a situation. Am I correct in assuming that the query was killed / rolled back? Is there any query running in the background? I've seen some related answers on this forum but wanted to specifically understand this for linked servers, as I use them a lot to retrieve data from other DBs for my job.
I'm more concerned about the Oracle DB as I don't want my query to impact any performance upstream. I only have a read-only access permission to the Oracle DB.
Thank you!
On shutdown the query will be aborted, and the INSERT rolled back. The rollback may happen during shutdown, or after restart, and may take some time to complete.
There's no automatic retry or anything that will access the linked server Oracle after the shutdown.

Using SAVE TRANSACTION with a linked server

Inside a transaction that have a savepoint I have to make a join with a table that is in a linked server. When I try to do it, I get the error message:
“Cannot use SAVE TRANSACTION within a distributed transaction”
The remote table data rarely changes. It is almost fixed. Is is possible to tell SqlServer to exclude this table from the transaction? I've tried a (NOLOCK) hint, but it isn't possible to use this hint for a table in a linked server.
Does anyone knows about a workaround? I'm using the ole SqlServer 2000.
One thing that you could do is to make a local copy of the remote table before you start the transaction. I know that this may sound like a lot of overhead, but remote joins are frequently a performance problem anyway and the SOP fix for that is also to make a local copy.
According to this link, the ability to use SAVEPOINTs in a Distributed transaction was dropped in SQL 7.
To allow application migration from Microsoft SQL Server 6.5 when
savepoints inside distributed transactions are in use, Microsoft SQL
Server 2000 Service Pack 1 introduces a trace flag that allows a
savepoint within a distributed transaction. The trace flag is 8599 and
can be turned on during the SQL Server startup or within an individual
session (that is, prior to enabling a distributed transaction with a
BEGIN DISTRIBUTED TRANSACTION statement) by using the DBCC TRACEON
command. When trace flag 8599 is set to ON, SQL Server allows you to
use a savepoint within a distributed transaction.
So unfortunately, you may either have to drop the bounding ACID transaction, or change the SPROC on the remote server so that it doesn't use SAVEPOINTs.
On a side note (Although I have seen that you have tagged it SQL SERVER 2000) but to make a point that SQL SERVER 2008 has remote proc trans Option for this.
In this case if the distributed table is not too large I would copy it to a temp table. If possible, include any filtering to get the number of rows to a minimum. Then you can proceed normally. Another option since the data changes rarely is copy the data to a permanant table and checking if anything has changed to prevent sending to much data over the network every time you run the transaction. You could only pull over the recent changes.
If you wish to handle transaction from UI level and you have Visual Studio 2008/.net fx 3.5 or + framework then you can wrap your logic with TransactionScope Class. If you dont have any frontends and you are working only on Sql Servers kindly ignore my answer...

Two simultaneous rollbacks deadlocking tables

Accidentally the same stored procedure was run twice at one time on our MS SQL Server 2008 R2. They were run from the same SQL Server Management Studio client and I tried to cancel them both. After 45 minutes neither process has cancelled. I read somewhere that it would help to close the query windows in SSMS so I did. However the tables the stored procedure should be writing to is still locked even though almost 20 hours has passed. I guess there is a deadlock. I hit cancel seconds after the stored procedure was initiated.
The table the stored procedure is reading from is not locked. The stored procedure is in CLR. It reads from a table, manipulate data and then use SqlBulkCopy to insert into three other tables.
The data in the tables the SP writes to can very easily be recreated. However I can neither drop nor truncate them due to the lock. I also tried KILL SPID with no result.
I have been thinking about restarting the server, but I guess it would not help because of SQL Servers data integrity.
I would really like some input on how release the lock. Several websites with lots of users depend on the database server so solutions that do not involve restarting would be much appreciated.

SQL Server 2005 SP Deadlock issue

I have a scheduled job with a SP running on daily basis (SQL Server 2005). Recently I frequently encounter deadlock problem for this SP. Here is the error message:
Message
Executed as user: dbo. Transaction (Process ID 56) was deadlocked on thread |
communication buffer resources with another process and has been chosen as the deadlock
victim. Rerun the transaction. [SQLSTATE 40001] (Error 1205). The step failed.
The SP uses some inter joined views to some tables, one of them is a large size data table with several million rows of data(and keep growing). I am not sure if any job or query against to the table will cause the SP un-accessible to the table? I am going to investigate who is on line by using the query. That may expose some query or person on SQL server during that time.
Not sure if any one have similar issue or this is known SQL 2005 issue? Any additional way I should do in my SP or on SQL server to avoid the deadlock?
Use the SQL Server Profiler to track all the queries that are running. I put the output into SQL Server. This will help you figure out which ones are accessing your particular table / tables. Post your findings, and we can help you with that.
Deadlocks are when two transactions are each holding onto some resources and want a resource that the other one has as well - neither can proceed as they are both waiting for each other. They cannot be completely eliminated, but a lot can be done to mitigate them. Remus and Raj suggest capturing more information about them in Profiler - which I also recommend - generally optimizing your queries (if you know which ones are involved) can also help. Here is an MSDN article that can help get you going: "Minimizing Deadlocks".

Resources