108

My PHP/MS Sql Server 2005/win 2003 Application occasionally becomes very unresponsive, the memory/cpu usage does not spike. If i try to open any new connection from sql management studio, then the it just hangs at the open connection dialog box. how to deterime the total number of active connections ms sql server 2005

Andy Lester
  • 91,102
  • 13
  • 100
  • 152

8 Answers8

300

This shows the number of connections per each DB:

SELECT 
    DB_NAME(dbid) as DBName, 
    COUNT(dbid) as NumberOfConnections,
    loginame as LoginName
FROM
    sys.sysprocesses
WHERE 
    dbid > 0
GROUP BY 
    dbid, loginame

And this gives the total:

SELECT 
    COUNT(dbid) as TotalConnections
FROM
    sys.sysprocesses
WHERE 
    dbid > 0

If you need more detail, run:

sp_who2 'Active'

Note: The SQL Server account used needs the 'sysadmin' role (otherwise it will just show a single row and a count of 1 as the result)

Boycs
  • 5,610
  • 2
  • 28
  • 23
Mitch Wheat
  • 295,962
  • 43
  • 465
  • 541
  • 2
    Wonderful thank you very much. For novices like me, start SQL Server Management Studio, right click on your database, select New Query, paste this in and click the "! Go" button. –  Dec 13 '12 at 22:05
  • 10
    This should be neither accepted, nor highest voted answer as it is simply incorrect. You can only rely on the returned number if you are logged in as `sa`. If you are logged in as a non-sa user, you will see 1 and that will not be representative of the actual connections. – ajeh Oct 14 '14 at 20:33
  • 5
    @ajeh: It's implicit that you have sufficient permissions to carry out the task. Your comment is redundant. – Mitch Wheat Oct 14 '14 at 23:54
  • 1
    @MitchWheat It's recommended to comment in your answer that to get actual/all connections of the SQL Server, the account used to run this script requires 'sysadmin' permission. – IEBasara Oct 28 '14 at 06:19
  • 2
    @ IEBasara: It's implicit. Why would you expect a non-admin to be able to view such information? – Mitch Wheat Oct 28 '14 at 06:26
  • 1
    Late to the party .. but .. the `sysadmin` role required (edit comment) saved my buttox. I kept getting 1 assuming I did have the right perms. Phew! fixed and sovled. *win* :money_with_wings: – Pure.Krome Sep 04 '15 at 02:15
8

Use this to get an accurate count for each connection pool (assuming each user/host process uses the same connection string)

SELECT 
DB_NAME(dbid) as DBName, 
COUNT(dbid) as NumberOfConnections,
loginame as LoginName, hostname, hostprocess
FROM
sys.sysprocesses with (nolock)
WHERE 
dbid > 0
GROUP BY 
dbid, loginame, hostname, hostprocess
realstrategos
  • 783
  • 8
  • 7
7

As @jwalkerjr mentioned, you should be disposing of connections in code (if connection pooling is enabled, they are just returned to the connection pool). The prescribed way to do this is using the 'using' statement:

// Execute stored proc to read data from repository
using (SqlConnection conn = new SqlConnection(this.connectionString))
{
    using (SqlCommand cmd = conn.CreateCommand())
    {
        cmd.CommandText = "LoadFromRepository";
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue("@ID", fileID);

        conn.Open();
        using (SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
        {
            if (rdr.Read())
            {
                filename = SaveToFileSystem(rdr, folderfilepath);
            }
        }
    }
}
Sebastian
  • 6,293
  • 6
  • 34
  • 47
Mitch Wheat
  • 295,962
  • 43
  • 465
  • 541
  • The asker mentioned they were using PHP, so the code sample may not be appropriate for them. The garbage collector should automatically cleans up non-persistent SQL Server connections when there are no more references to them (and all references would be dropped at the end of the page cycle), but maybe the asker is using persistent connections, which requires intelligent connection reuse. – Paul d'Aoust Jul 18 '14 at 17:26
5

I know this is old, but thought it would be a good idea to update. If an accurate count is needed, then column ECID should probably be filtered as well. A SPID with parallel threads can show up multiple times in sysprocesses and filtering ECID=0 will return the primary thread for each SPID.

SELECT 
    DB_NAME(dbid) as DBName, 
    COUNT(dbid) as NumberOfConnections,
    loginame as LoginName
FROM
    sys.sysprocesses with (nolock)
WHERE 
    dbid > 0
    and ecid=0
GROUP BY 
    dbid, loginame
sqldba.today
  • 51
  • 1
  • 1
1

If your PHP app is holding open many SQL Server connections, then, as you may know, you have a problem with your app's database code. It should be releasing/disposing those connections after use and using connection pooling. Have a look here for a decent article on the topic...

http://www.c-sharpcorner.com/UploadFile/dsdaf/ConnPooling07262006093645AM/ConnPooling.aspx

Seth Flowers
  • 8,990
  • 2
  • 29
  • 42
jwalkerjr
  • 1,779
  • 4
  • 18
  • 20
0

see sp_who it gives you more details than just seeing the number of connections

in your case i would do something like this

 DECLARE @temp TABLE(spid int , ecid int, status varchar(50),
                     loginname varchar(50),   
                     hostname varchar(50),
blk varchar(50), dbname varchar(50), cmd varchar(50), request_id int) 
INSERT INTO @temp  

EXEC sp_who

SELECT COUNT(*) FROM @temp WHERE dbname = 'DB NAME'
Mina Gabriel
  • 23,150
  • 26
  • 96
  • 124
0

MS SQL knowledge based - How to know open SQL database connection(s) and occupied on which host.

Using below query you will find list database, Host name and total number of open connection count, based on that you will have idea, which host has occupied SQL connection.

SELECT DB_NAME(dbid) as DBName, hostname ,COUNT(dbid) as NumberOfConnections
FROM sys.sysprocesses with (nolock) 
WHERE dbid > 0 
and len(hostname) > 0 
--and DB_NAME(dbid)='master' /* Open this line to filter Database by Name */
Group by DB_NAME(dbid),hostname
order by DBName
0
SELECT
[DATABASE] = DB_NAME(DBID), 
OPNEDCONNECTIONS =COUNT(DBID),
[USER] =LOGINAME
FROM SYS.SYSPROCESSES
GROUP BY DBID, LOGINAME
ORDER BY DB_NAME(DBID), LOGINAME