SQL Server SPID doesnt change for every connection - sql-server

We are building an ERP system, and sometimes we need to see the SQL statement in SQL Server Profiler for debuging purposes. I can catch my ERP's queries by the SPID on Profiler. My ERP doesnt keep an open connection, it opens a connection everytime it needs it.
I have been thinking that everytime my ERP opens a connection, it should get a new SPID. How does it give the same SPID?

SPIDs are recycled, they are guaranteed to be unique at any one time, but if a connection drops, its SPID can be reused by a new connection.

Related

SQL Server Log - Souce (SPID)

In checking Log File Viewer for noteworthy events I came across a log that I wanted to investigate.
Let's say the log notes the Source as SPID1234
My question:
Is this SPID tied to the actual connection that generated the log or is the SPID associated with the process that is writing this to the log?
In your scenario, the SPID1234, which means the session that is running this command has ID of 1234.
from here
A SPID in SQL Server is a Server Process ID. These process ID’s are
essentially sessions in SQL Server. Everytime an application connects
to SQL Server, a new connection (or SPID) is created. This connection
has a defined scope and memory space and cannot interact with other
SPIDs. The term SPID is synonymous with Connection, or Session.
SPID in Transaction Log - is ID of the process which originated the transaction, which was written into Transaction Log

Why can i still make request while the server is disconnected?

I'm using SQL Server Management Studio.
I log in my server, open a "new request" window and write a query that select ALL the element of a table.
SQL Server then display a table with the content queried.
However, as this request work when i'm connected, which is perfectly logic, i don't understand why this request still work when i disconnect from the server.
Is it a normal behavior ? When i disconnect from a server it's specifically to not execute a query by accident.
When you say disconnect, do you mean on your server connection on the left plane or on the current query you are on? Because a query can be open with a seperate connection to a database than from your left databases pane. It can be empty because that list's connection has been disconnected but the queries that are open run in a separate window and use a seperate connection –
Right click on your query window, go to connection and select disconnect then the query will not be able to run
When you open a query on the current database they will use the connection details, but they use a seperate connection to the database, so if you close your conneciton on the left databases pane. your query still has its own connection open
Most probably the query result is cashed for better performance. That is why for the next select it doesn't use the connection, just the cashed result. You can even add the where condition and it will work.

SQL Server - How to prevent sql server from disconnect the idle connection after period of time?

i am using sql server 2012 with desktop application as client , the application get errors after period of time when no activity on it , i googled about this issue all solutions points me to AUTO_CLOSE option on database but it's already set to false .
i thing is something missing in connection string (ADO Extension)
To be honest, if you have long running connections, you can hit these errors regardless due to firewalls / routers closing connections, etc. The correct solution is to instantiate a connection when you need it, use the connection and release it. With connection pooling, this is not really a performance problem.
If your long-running application is "bursty", it is sometimes convenient to open the connection, do a number of commands -- then when you go idle, release the connection and wait the next burst of activity.

Drop all active database connections failed for Server when executing KillAllProcesses

I need to perform a database restore from my application. Before doing this, I want to kill all processes as follows:
private void KillAllProcessesOnSMARTDatabases(Server targetServer)
{
targetServer.KillAllProcesses(SMART_DB);
targetServer.KillAllProcesses(SMART_HISTORY_DB);
targetServer.KillAllProcesses(SMART_METADATA_DB);
SqlConnection.ClearAllPools();
}
However, when the first KillAllProcesses is run, I get the following exception:
Microsoft.SqlServer.Management.Smo.FailedOperationException: Drop all active database connections failed for Server 'MYServer'. ---> Microsoft.SqlServer.Management.Common.ExecutionFailureException: An exception occurred while executing a Transact-SQL statement or batch. ---> System.Data.SqlClient.SqlException: Only user processes can be killed.
The connection string used to create the server has sa credentials, however, the processes that need to be terminated are started under a different user. I tested the similar scenario and the test succeeded.
This started happening only recently. To me it appears there are some processes running that are not started by the user?
It would appear that your code is attempting to terminate all SQL Server Processes, which is not a good idea.
If you want to perform a database restore, you should set the database in question into either single_user mode or RESTRICTED_USER mode, the later being the most suitable.
Take a look at the following example of switching a database to RESTRICTED_USER mode and how to close any open user connections in the process.
How to: Set a Database to Single-User mode
You can use SMO to "kill" a particular database.
This will force a drop of all client connections to that database only and then drop the database itself.
Microsoft.SqlServer.Management.Smo.Server oServer = this.GetSmoServer();
oServer.KillDatabase(this.DatabaseName);

Extreme wait-time when taking a SQL Server database offline

I'm trying to perform some offline maintenance (dev database restore from live backup) on my dev database, but the 'Take Offline' command via SQL Server Management Studio is performing extremely slowly - on the order of 30 minutes plus now. I am just about at my wits end and I can't seem to find any references online as to what might be causing the speed problem, or how to fix it.
Some sites have suggested that open connections to the database cause this slowdown, but the only application that uses this database is my dev machine's IIS instance, and the service is stopped - there are no more open connections.
What could be causing this slowdown, and what can I do to speed it up?
After some additional searching (new search terms inspired by gbn's answer and u07ch's comment on KMike's answer) I found this, which completed successfully in 2 seconds:
ALTER DATABASE <dbname> SET OFFLINE WITH ROLLBACK IMMEDIATE
(Update)
When this still fails with the following error, you can fix it as inspired by this blog post:
ALTER DATABASE failed because a lock could not be placed on database 'dbname' Try again later.
you can run the following command to find out who is keeping a lock on your database:
EXEC sp_who2
And use whatever SPID you find in the following command:
KILL <SPID>
Then run the ALTER DATABASE command again. It should now work.
There is most likely a connection to the DB from somewhere (a rare example: asynchronous statistic update)
To find connections, use sys.sysprocesses
USE master
SELECT * FROM sys.sysprocesses WHERE dbid = DB_ID('MyDB')
To force disconnections, use ROLLBACK IMMEDIATE
USE master
ALTER DATABASE MyDB SET SINGLE_USER WITH ROLLBACK IMMEDIATE
Do you have any open SQL Server Management Studio windows that are connected to this DB?
Put it in single user mode, and then try again.
In my case, after waiting so much for it to finish I had no patience and simply closed management studio. Before exiting, it showed the success message, db is offline. The files were available to rename.
execute the stored procedure
sp_who2
This will allow you to see if there is any blocking locks.. kill their should fix it.
In SSMS: right-click on SQL server icon, Activity Monitor. Open Processes. Find the processed connected. Right-click on the process, Kill.
In my case I had looked at some tables in the DB prior to executing this action. My user account was holding an active connection to this DB in SSMS. Once I disconnected from the server in SSMS (leaving the 'Take database offline' dialog box open) the operation succeeded.
anytime you run into this type of thing you should always think of your transaction log. The alter db statment with rollback immediate indicates this to be the case. Check this out: http://msdn.microsoft.com/en-us/library/ms189085.aspx
Bone up on checkpoints, etc. You need to decide if the transactions in your log are worth saving or not and then pick the mode to run your db in accordingly. There's really no reason for you to have to wait but also no reason for you to lose data either - you can have both.
Closing the instance of SSMS (SQL Service Manager) from which the request was made solved the problem for me.....
To get around this I stopped the website that was connected to the db in IIS and immediately the 'frozen' 'take db offline' panel became unfrozen.
Also, close any query windows you may have open that are connected to the database in question ;)
I tried all the suggestions below and nothing worked.
EXEC sp_who
Kill < SPID >
ALTER DATABASE SET SINGLE_USER WITH Rollback Immediate
ALTER DATABASE SET OFFLINE WITH ROLLBACK IMMEDIATE
Result: Both the above commands were also stuck.
4 . Right-click the database -> Properties -> Options
Set Database Read-Only to True
Click 'Yes' at the dialog warning SQL Server will close all connections to the database.
Result: The window was stuck on executing.
As a last resort, I restarted the SQL server service from configuration manager and then ran ALTER DATABASE SET OFFLINE WITH ROLLBACK IMMEDIATE. It worked like a charm
In SSMS, set the database to read-only then back. The connections will be closed, which frees up the locks.
In my case there was a website that had open connections to the database. This method was easy enough:
Right-click the database -> Properties -> Options
Set Database Read-Only to True
Click 'Yes' at the dialog warning SQL Server will close all connections to the database.
Re-open Options and turn read-only back off
Now try renaming the database or taking it offline.
For me, I just had to go into the Job Activity Monitor and stop two things that were processing. Then it went offline immediately. In my case though I knew what those 2 processes were and that it was ok to stop them.
In my case, the database was related to an old Sharepoint install. Stopping and disabling related services in the server manager "unhung" the take offline action, which had been running for 40 minutes, and it completed immediately.
You may wish to check if any services are currently utilizing the database.
Next time, from the Take Offline dialog, remember to check the 'Drop All Active Connections' checkbox. I was also on SQL_EXPRESS on local machine with no connections, but this slowdown happened for me unless I checked that checkbox.
SSMS, especially if running it from your own desktop remotely and not directly within the database server, can be a reason for the long delays in detaching a database. For some reason SSMS may not be able to disconnect any existing "connections" to the database.
We found the process was almost instant when we did it directly from the database server itself. And in fact it killed the attempt from my own desktop SSMS session, and it "took over" and detached the database.
Nothing else suggested here worked.
Thanks
In my case i stopped Tomcat server . then immediately the DB went offline .

Resources