Help with SQL Script for connection + extended attribute

All we need is an easy explanation of the problem, so here it is.

I am trying to find out which of the DB don’t have active connection and the extended attribute of that DB.
I have this script that works wonderfully and creates a table with all DBs name and the amount of active connection.
Can someone please assist how to I add an additional column that will show the extended attribute called "Test" for each DB?

SELECT @@ServerName AS server
 ,NAME AS dbname
 ,COUNT(STATUS) AS  number_of_connections
 ,GETDATE() AS timestamp
FROM sys.databases sd
LEFT JOIN sysprocesses sp ON sd.database_id = sp.dbid
WHERE database_id NOT BETWEEN 1 AND 4
GROUP BY NAME

Thanks!
Effy L.

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

Extended properties are database-scoped so you’ll need to query values in the context of each database.

The below example uses dynamic SQL to accomplish this by qualifying sys.extended_properties with the name of each database and concatenating results for all databases with UNION ALL. This also uses sys.dm_exec_sessions instead of the sysprocesses view as recommended in the documentation. You may need to tweak the query according to your use case and environment (e.g. omit non-readable secondary AG replicas).

DECLARE @SQL nvarchar(MAX);

WITH databases AS (
    SELECT sd.name, sd.database_id
    FROM sys.databases sd 
    WHERE sd.database_id > 4 AND state_desc = 'ONLINE'
)
SELECT @SQL = STRING_AGG(CAST(N'
SELECT 
      @@SERVERNAME AS server
    , N' + QUOTENAME(d.name,'''') + N' AS dbname
    , (SELECT COUNT(1) FROM sys.dm_exec_sessions AS sdes WHERE sdes.database_id = ' + CAST(d.database_id AS nvarchar(10)) + N') AS number_of_connections
    , SYSDATETIME() AS timestamp
    , (SELECT value FROM ' + QUOTENAME(d.name) + N'.sys.extended_properties WHERE class_desc = N''DATABASE'' AND name = N''Test'') AS TestExtendedPropertyValue'
    AS nvarchar(MAX))
    ,' UNION ALL')
FROM databases AS d;

--SELECT @SQL;
EXEC sp_executesql @SQL;
GO

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply