Export SQL Server info about disk, cpu and memory utilization - sql-server

I am trying to use logstash to read log files. When it come to monitor SQL Server, is there anyway to export SQL Server Database Disk Usage data to a log file?

Disk usage (per database):
IF OBJECT_ID('tempdb.dbo.#space') IS NOT NULL
DROP TABLE #space
CREATE TABLE #space (
database_id INT PRIMARY KEY
, data_used_size DECIMAL(18,2)
, log_used_size DECIMAL(18,2)
)
DECLARE #SQL NVARCHAR(MAX)
SELECT #SQL = STUFF((
SELECT '
USE [' + d.name + ']
INSERT INTO #space (database_id, data_used_size, log_used_size)
SELECT
DB_ID()
, SUM(CASE WHEN [type] = 0 THEN space_used END)
, SUM(CASE WHEN [type] = 1 THEN space_used END)
FROM (
SELECT s.[type], space_used = SUM(FILEPROPERTY(s.name, ''SpaceUsed'') * 8. / 1024)
FROM sys.database_files s
GROUP BY s.[type]
) t;'
FROM sys.databases d
WHERE d.[state] = 0
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 2, '')
EXEC sys.sp_executesql #SQL
SELECT
d.database_id
, d.name
, d.state_desc
, t.total_size
, t.data_size
, s.data_used_size
, t.log_size
, s.log_used_size
FROM (
SELECT
database_id
, log_size = CAST(SUM(CASE WHEN [type] = 1 THEN size END) * 8. / 1024 AS DECIMAL(18,2))
, data_size = CAST(SUM(CASE WHEN [type] = 0 THEN size END) * 8. / 1024 AS DECIMAL(18,2))
, total_size = CAST(SUM(size) * 8. / 1024 AS DECIMAL(18,2))
FROM sys.master_files
GROUP BY database_id
) t
JOIN sys.databases d ON d.database_id = t.database_id
LEFT JOIN #space s ON d.database_id = s.database_id
ORDER BY t.total_size DESC
Disk activity:
IF OBJECT_ID('tempdb.dbo.#tt', 'U') IS NULL
CREATE TABLE #tt (
tm DATETIME PRIMARY KEY,
total_read NUMERIC(28, 2),
total_written NUMERIC(28, 2),
total_io_count BIGINT,
total_io_wait BIGINT
)
DECLARE #current_collection_time DATETIME = GETDATE()
INSERT INTO #tt
SELECT
#current_collection_time,
SUM(num_of_bytes_read / 1024.0 / 1024.0 ),
SUM(num_of_bytes_written / 1024.0 / 1024.0 ),
SUM(num_of_reads + num_of_writes),
SUM(io_stall)
FROM sys.dm_io_virtual_file_stats(DEFAULT, DEFAULT)
DECLARE #previous_collection_time DATETIME
SELECT #previous_collection_time = tm
FROM #tt
WHERE tm < #current_collection_time
DECLARE #interval_ms INT = DATEDIFF(MILLISECOND, #previous_collection_time, #current_collection_time);
SELECT
read_mb_sec = (c.total_read - p.total_read) * 1000 / #interval_ms,
write_mp_sec = (c.total_written - p.total_written) * 1000 / #interval_ms,
response_time_ms =
CASE
WHEN (c.total_io_count - p.total_io_count) = 0
THEN 0
ELSE (c.total_io_wait - p.total_io_wait) / (c.total_io_count - p.total_io_count)
END
FROM #tt c
CROSS JOIN #tt p
WHERE c.tm = #current_collection_time
AND p.tm = #previous_collection_time
DELETE FROM #tt
WHERE tm < #current_collection_time;
Memory utilization:
DECLARE #sql_memory_mb INT
SELECT #sql_memory_mb = physical_memory_in_use_kb / 1024
FROM sys.dm_os_process_memory
SELECT
total_memory_mb = total_physical_memory_kb / 1024,
memory_in_use_mb = (total_physical_memory_kb - available_physical_memory_kb) / 1024,
sql_memory_mb = #sql_memory_mb
FROM sys.dm_os_sys_memory
CPU utilization:
SELECT
cpu_total =
CASE WHEN cpu_sql > cpu_total AND cpu_sql <= 99.
THEN cpu_sql
ELSE cpu_total
END,
cpu_sql
FROM (
SELECT cpu_total = 100 - x.value('(./Record/SchedulerMonitorEvent/SystemHealth/SystemIdle/text())[1]', 'TINYINT')
FROM (
SELECT TOP(1) [timestamp], x = CONVERT(XML, record)
FROM sys.dm_os_ring_buffers
WHERE ring_buffer_type = N'RING_BUFFER_SCHEDULER_MONITOR'
AND record LIKE '%<SystemHealth>%'
) t
) x
CROSS JOIN (
SELECT
cpu_sql = (
MAX(CASE WHEN counter_name = 'CPU usage %' THEN t.cntr_value * 1. END) /
MAX(CASE WHEN counter_name = 'CPU usage % base' THEN t.cntr_value END)
) * 100
FROM (
SELECT TOP(2) cntr_value, counter_name
FROM sys.dm_os_performance_counters
WHERE counter_name IN ('CPU usage %', 'CPU usage % base')
AND instance_name = 'default'
) t
) t
This queries you can run from jobs and put required information into tables.
How to load data into file:
/*
EXEC sys.sp_configure 'show advanced options', 1
GO
RECONFIGURE
GO
EXEC sys.sp_configure 'xp_cmdshell', 1
GO
RECONFIGURE WITH OVERRIDE
GO
*/
DECLARE #sql NVARCHAR(4000) = 'bcp "SELECT * FROM dbo.disk_activity" queryout "D:\sample.html" -S ' + ##servername + ' -T -w -r -t'
EXEC sys.xp_cmdshell #sql

Related

Optimise a Stored procedure in SQL? Facing Error

Can someone help me to optimise this SP as it takes more than 3 minutes to run and then it gives Timeout error. "Execution Timeout Expired. The timeout period elapsed prior to completion of the operation or the server is not responding." I am a beginner and would like to optimise the below SP because it takes forever to give results and it also gives timeout error. I tried putting indexing to temp tables but unsuccessful. Help !!!!
ALTER PROCEDURE GetCompanyByCandidatetest
#USER_ID VARCHAR(50) = NULL
AS
BEGIN
declare #statenew varchar(1000) = Null
declare #countnew varchar(1000) = Null
declare #STRSQLNew varchar(max)
declare #STRSQL4 varchar(max)
declare #state1 varchar(1000) = Null ,#ind varchar(1000) = Null,#Distinct varchar(1000) = Null,#Dist1 varchar(1000) = Null,
#EQuit_ID varchar(1000) = Null,#Degree_ID varchar(100) = Null,#Isguest varchar(100) = Null,#verified varchar(100) = Null,
#keyword varchar(100) = Null,#workexperience varchar(100) = Null,#prefcity varchar(100) = Null,#addcity varchar(100) = Null,
#Key_skill varchar(100) = Null,#CURRENT_DEPARTMENT varchar(100),#PREF_DEPARTMENT varchar(100),#CURRENT_DESIGNATION varchar(100),#PREF_DESIGNATION varchar(100),#indcurr varchar(100)
select #Isguest = isnull(guest_login,0), #verified = isnull(VERIFIED,0) from mtb_frinds where user_id = #USER_ID
select #statenew = isnull(PREF_STATE,''),#state1 = isnull(ADD_STATE,''),#Distinct = isnull(PREF_DISTRICT,''),#Distinct1 = isnull(add_dist,''),
#ind = isnull(PREF_INDUSTRY,''),#indcurr=isnull(CURRENT_INDUSTRY,'') ,#EQuit_ID = isnull(EQ_ID,'') ,#keyword=isnull(key_word,'') ,#workexperience=isnull(WORK_EXPYEARS,''),#CURRENT_DEPARTMENT=isnull(CURRENT_DEPARTMENT,''), #PREF_DEPARTMENT=isnull(PREF_DEPARTMENT,''),
#prefcity=isnull(PREF_CITY,'') ,#addcity=ADD_CITY,#Key_skill=isnull(Key_skill,''),#CURRENT_DESIGNATION=isnull(CURRENT_DESIGNATION,''),#PREF_DESIGNATION=isnull(PREF_DESIGNATION,'')
from mtb_frinds where USER_ID = #USER_ID
if(#statenew!='' and #Key_skill !='' and #state1 !='' and #keyword !='' )
begin
print 'ind' +#ind
print '#indcurr' +#indcurr
print '#PREF_DEPARTMENT'+ #PREF_DEPARTMENT
print '#CURRENT_DEPARTMENT'+#CURRENT_DEPARTMENT
print '#keyword'+ #keyword
set #STRSQLNew='
select ej_id, EQ_ID, JOB_STATUS ,job_desc,
active, USER_ID, JOB_TITLE, CREATED_ON,
REQUIRED_MP, WORK_EXPYEARS, SALARY, IND_ID,
Key_skill, STATE_ID, DIST_ID, LOCALITY_ID,
DEPT_ID,1 as Priority, EXPIRATION_DATE
into #dummy from mtb_jobs Ek
'
IF #EQuit_ID IS NOT NULL AND #EQuit_ID != ''
BEGIN
print 1
SET #STRSQLNew = #STRSQLNew + ' CROSS APPLY dbo.Split(EQ_ID,'','') AS A
CROSS APPLY dbo.Split('''+#EQuit_ID+''','','') AS B'
set #STRSQL4 ='(((A.items = B.items) or '
END
IF #keyword IS NOT NULL AND #keyword != ''
BEGIN
print 2
SET #STRSQLNew = #STRSQLNew + ' CROSS APPLY dbo.Split(keywords,'','') AS e
CROSS APPLY dbo.Split('''+#keyword+''','','') AS f'
set #STRSQL4 =#STRSQL4+'(e.items =f.items)) and '
END
IF #statenew IS NOT NULL AND #statenew != ''
BEGIN
print 3
SET #STRSQLNew = #STRSQLNew + ' CROSS APPLY dbo.Split(STATE_ID,'','') AS i
CROSS APPLY dbo.Split('''+#statenew+''','','') AS j'
set #STRSQL4 = #STRSQL4+'((i.items =j.items) '
END
IF #state1 IS NOT NULL AND #state1 != ''
BEGIN
print 4
SET #STRSQLNew = #STRSQLNew + ' CROSS APPLY dbo.Split(STATE_ID,'','') AS k
CROSS APPLY dbo.Split('''+#state1+''','','') AS l'
set #STRSQL4 =#STRSQL4+' or (k.items =l.items)) and '
END
IF #Key_skill IS NOT NULL AND #Key_skill != ''
BEGIN
print 5
SET #STRSQLNew = #STRSQLNew + ' CROSS APPLY dbo.Split(Key_skill,'','') AS g
CROSS APPLY dbo.Split('''+#Key_skill+''','','') AS h'
set #STRSQL4 =#STRSQL4+' ((g.items =h.items) or
'
END
set #STRSQLNew = #STRSQLNew+ ' where '+ #STRSQL4 +'(DEPT_ID in (select items from dbo.split('''+#CURRENT_DEPARTMENT+''','','')) or DEPT_ID in (select items from dbo.split('''+#PREF_DEPARTMENT+''','','')))))
or(e.items =f.items and ((k.items =l.items) or (i.items =j.items) ))
'
set #STRSQLNew =#STRSQLNew+ ' select * into #temp from ( select max(ej_id) as ej_id , max(EQ_ID) as EQ_ID, max(JOB_STATUS) as JOB_STATUS , max(job_desc) as job_desc,max(active) as active, max(USER_ID) as USER_ID ,max(JOB_TITLE) as JOB_TITLE ,max(CREATED_ON) as CREATED_ON ,max(REQUIRED_MP) as REQUIRED_MP ,max(WORK_EXPYEARS) as WORK_EXPYEARS ,
max(SALARY) as SALARY ,max(IND_ID) as IND_ID ,max(Key_skill) as Key_skill , max(STATE_ID) as STATE_ID ,max(DIST_ID) as DIST_ID,max(LOCALITY_ID) as LOCALITY_ID ,max(DEPT_ID) as DEPT_ID,2 as Priority,max(EXPIRATION_DATE) as EXPIRATION_DATE from #dummy where EXPIRATION_DATE >0 group by ej_id
) as x '
set #STRSQLNew =#STRSQLNew+' select * into #Temp2 from
(
select a.ej_id, isnull(a.JOB_TITLE,'''') as JOB_TITLE, isnull(b.ENT_NAME,'''') as ENT_NAME, CASE
WHEN DATEDIFF(SECOND, a.CREATED_ON, GETDATE()) < 60 THEN ''Just Posted''
WHEN DATEDIFF(MINUTE, a.CREATED_ON, GETDATE()) < 60 THEN CAST(DATEDIFF(MINUTE, a.CREATED_ON, GETDATE()) AS VARCHAR(10)) + '' Minutes ago''
WHEN DATEDIFF(MINUTE, a.CREATED_ON, GETDATE()) < 24 * 60 THEN CAST(FLOOR(DATEDIFF(MINUTE, a.CREATED_ON, GETDATE())/60) AS VARCHAR(10)) + '' Hours ago''
ELSE CAST(FLOOR(DATEDIFF(HOUR, a.CREATED_ON, GETDATE())/24) AS VARCHAR(10)) + ''Days ago''
END AS POSTED_ON,a.REQUIRED_MP,''1'' as Issuitable,a.job_desc, a.created_on,DATEDIFF(DAY,GETDATE(),a.EXPIRATION_DATE) as EXPIRATION_DATE
,isnull('''+#Isguest+''',''0'') as Isguest,isnull('''+#verified+''',''0'') as Isverified
,isnull(cnt,0) as Isapplied,substring(
(
Select distinct '', ''+ ST1.StateName AS [text()]
From MTB_STATESNEW ST1
Where ST1.StateId in (select items from dbo.split (a.state_id,'',''))
For XML PATH ('''')
), 2, 1000000) [StateName],
substring(
(
Select distinct '', ''+ min(convert(varchar(1000),ST1.MIN_EXP)) AS [text()]
From dbo.MTB_WORKEXP ST1
Where ST1.EXP_ID in (select items from dbo.split (a.WORK_EXPYEARS,'',''))
For XML PATH ('''')
), 2, 1000000) [min_exp],
substring(
(
Select distinct '',''+ max(convert(varchar(1000),ST1.MAX_EXP)) AS [text()]
From dbo.MTB_WORKEXP ST1
Where ST1.EXP_ID in (select items from dbo.split (a.WORK_EXPYEARS,'',''))
For XML PATH ('''')
), 2, 1000000) [max_exp],
substring(
(
Select distinct '', ''+ min(convert(varchar(1000),ST1.SR_MIN)) AS [text()]
From dbo.MTB_SALARYRANGE ST1
Where ST1.SR_ID in (select min(items) from dbo.split (a.SALARY,'',''))
For XML PATH ('''')
), 2, 1000000) [min_Salary],
substring(
(
Select distinct '',''+ max(convert(varchar(1000),ST1.sr_max)) AS [text()]
From dbo.MTB_SALARYRANGE ST1
Where ST1.SR_ID in (select items from dbo.split (a.SALARY,'',''))
For XML PATH ('''')
), 2, 1000000) [max_Salary],
substring(
(
Select distinct '',''+ (convert(varchar(1000),ST1.KEY_SKILL)) AS [text()]
From MTB_KEYSKILL ST1
Where ST1.KEYSKILL_ID in (select items from dbo.split (a.Key_skill,'',''))
For XML PATH ('''')
), 2, 1000000) [KEY_SKILL]
,
substring (
(Select distinct '',''+ (convert(varchar(1000),ST1.KEYWORDS)) AS [text()]
From mtb_keywords ST1 where st1.KEYWORD_ID in ( select items from dbo.split('''+#keyword+''','',''))
For XML PATH ('''')
), 2, 1000000) [KEY_Word],
substring (
(Select distinct '',''+ (convert(varchar(1000),ST1.DIST_NAME)) AS [text()]
From MTB_DISTSNEW ST1 where st1.DIST_ID in ( select items from dbo.split(a.DIST_ID,'',''))
For XML PATH ('''')
), 2, 1000000) [dist_name],
substring(
(select distinct '',''+(convert(varchar(1000),ST1.EQ_NAME)) as [text()]
from MTB_EDUQUALIFICATIONS ST1 where st1.EQ_ID in (select items from dbo.split(a.EQ_ID,'',''))
For XML PATH('''')
),2,1000000) [EQ_Name],
substring(
(select distinct '',''+(convert(varchar(1000),ST1.IND_NAME)) as [text()]
from mtb_industry ST1 where st1.ind_id in (select items from dbo.split(a.ind_id,'',''))
For XML PATH('''')
),2,1000000) [IND_NAME]
from #temp as a inner join MTB_ENTERPRISES as b on a.user_id = b.user_id
left join (select count (ej_id) as cnt,ej_id from TTB_JOBAPPLICATIONS where USER_ID = '''+#USER_ID+''' group by EJ_ID) as ER on ER.EJ_ID = a.EJ_ID
where( a.JOB_STATUS = 1 and a.active = 1 )
) as x'
set #STRSQLNew =#STRSQLNew+' SELECT *,isnull(min_exp,'''') +''-''+ isnull(max_exp,'''') as WORK_EXP,isnull(min_Salary,'''') +''-''+ isnull(max_salary,'''') as Salary FROM #Temp2 '
print #STRSQLNew
exec (#STRSQLNew)
select 1 as ispara1, 'Sucess' as Msg ,1 as n
end
else
begin
select top 0* from MTB_ENTERPRISES
select 0 as ispara2, 0 as n,'Some fields are Incomplete' as Msg
end
END
Error:- Execution Timeout Expired. The timeout period elapsed prior to completion of the operation or the server is not responding.

T SQL Top 10 list of NULL Columns from a table

I'm using SQL Server 2014. I have a table with multiple columns in. Is it possible to dynamically list the top 10 columns within the table and the percent of the records in each column that is NULL? I do not want to hard code each column name in.
So the result set would be like:
Column Percent_Null
ABC 100
QWE 75
REW 65
TRW 50
I've started with the below, but how I do get this in a list? Ultimately the results need to go into a table for reporting.
DECLARE #SQL NVARCHAR(MAX)
SELECT #SQL = STUFF((
SELECT ', CAST(SUM(CASE WHEN ' + Quotename(C.COLUMN_NAME) + ' IS NULL THEN 1 ELSE 0 END) * 100.00
/#TotalCount AS INT) AS [' + C.COLUMN_NAME + ' NULL %]
'
FROM INFORMATION_SCHEMA.COLUMNS C
WHERE TABLE_NAME = 'tblMYTable'
AND TABLE_SCHEMA = 'dbo'
ORDER BY C.ORDINAL_POSITION
FOR XML PATH('')
,type
).value('.', 'nvarchar(max)'), 1, 2, '')
PRINT #SQL
Blargh, this is ugly, but it appears to do what you're after:
DECLARE #Table sysname = N'icp_yyclient',
#Schema sysname = N'dbo';
DECLARE #SQL nvarchar(MAX),
#CRLF nchar(2) = NCHAR(13) + NCHAR(10);
--First get a Count, which will be one column per column
SET #SQL = N'WITH Counts AS(' + #CRLF +
N' SELECT ' +
STUFF((SELECT N',' + #CRLF +
N' (COUNT(CASE WHEN ' + QUOTENAME(C.[name]) + N' IS NULL THEN 1 END) * 1.) / COUNT(*) AS ' + QUOTENAME(c.[name] + N'_PercNULL')
FROM sys.schemas s
JOIN sys.tables t ON s.schema_id = t.schema_id
JOIN sys.columns c ON t.object_id = c.object_id
WHERE s.name = #Schema
AND t.name = #Table
ORDER BY c.column_id
FOR XML PATH(N''),TYPE).value('.','nvarchar(MAX)'),1,14,N'') + #CRLF +
N' FROM ' + QUOTENAME(#Schema) + N'.' + QUOTENAME(#Table) + N')' + #CRLF +
--Now that we have a COUNT of column, we need to unpivot the data
N'SELECT TOP(10) V.*' + #CRLF +
N'FROM Counts C' + #CRLF +
N' CROSS APPLY(VALUES' +
STUFF((SELECT N',' + #CRLF +
N' (N' + QUOTENAME(C.[name],'''') + N', C.' + QUOTENAME(c.[name] + N'_PercNULL') + N')'
FROM sys.schemas s
JOIN sys.tables t ON s.schema_id = t.schema_id
JOIN sys.columns c ON t.object_id = c.object_id
WHERE s.name = #Schema
AND t.name = #Table
ORDER BY c.column_id
FOR XML PATH(N''),TYPE).value('.','nvarchar(MAX)'),1,26,N'') + N')V(ColumnName,ColumnPercNULL)' + #CRLF +
N'ORDER BY V.ColumnPercNULL DESC;';
--Uncommon to see the "mess". I strongly suggest ensuring you have retain CR/LF on in SSMS
--SELECT #SQL; --PRINT is limited to 4,000 characters, so probably too small.
EXEC sp_executesql #SQL;
For a table I have, (called Asset) this creates the following statement:
WITH Counts AS(
SELECT (COUNT(CASE WHEN [AssetID] IS NULL THEN 1 END) * 1.) / COUNT(*) AS [AssetID_PercNULL],
(COUNT(CASE WHEN [AssetName] IS NULL THEN 1 END) * 1.) / COUNT(*) AS [AssetName_PercNULL],
(COUNT(CASE WHEN [TypeID] IS NULL THEN 1 END) * 1.) / COUNT(*) AS [TypeID_PercNULL],
(COUNT(CASE WHEN [SerialNumber] IS NULL THEN 1 END) * 1.) / COUNT(*) AS [SerialNumber_PercNULL],
(COUNT(CASE WHEN [BarcodeNumber] IS NULL THEN 1 END) * 1.) / COUNT(*) AS [BarcodeNumber_PercNULL],
(COUNT(CASE WHEN [Manufacturer] IS NULL THEN 1 END) * 1.) / COUNT(*) AS [Manufacturer_PercNULL],
(COUNT(CASE WHEN [Model] IS NULL THEN 1 END) * 1.) / COUNT(*) AS [Model_PercNULL],
(COUNT(CASE WHEN [LocationID] IS NULL THEN 1 END) * 1.) / COUNT(*) AS [LocationID_PercNULL],
(COUNT(CASE WHEN [IPAddress] IS NULL THEN 1 END) * 1.) / COUNT(*) AS [IPAddress_PercNULL],
(COUNT(CASE WHEN [PurchaseDate] IS NULL THEN 1 END) * 1.) / COUNT(*) AS [PurchaseDate_PercNULL],
(COUNT(CASE WHEN [SetupDate] IS NULL THEN 1 END) * 1.) / COUNT(*) AS [SetupDate_PercNULL],
(COUNT(CASE WHEN [DecommissionDate] IS NULL THEN 1 END) * 1.) / COUNT(*) AS [DecommissionDate_PercNULL],
(COUNT(CASE WHEN [ReasonID] IS NULL THEN 1 END) * 1.) / COUNT(*) AS [ReasonID_PercNULL],
(COUNT(CASE WHEN [DecommissionBy] IS NULL THEN 1 END) * 1.) / COUNT(*) AS [DecommissionBy_PercNULL],
(COUNT(CASE WHEN [InvoiceID] IS NULL THEN 1 END) * 1.) / COUNT(*) AS [InvoiceID_PercNULL],
(COUNT(CASE WHEN [IsVirtual] IS NULL THEN 1 END) * 1.) / COUNT(*) AS [IsVirtual_PercNULL],
(COUNT(CASE WHEN [HostAssetID] IS NULL THEN 1 END) * 1.) / COUNT(*) AS [HostAssetID_PercNULL],
(COUNT(CASE WHEN [DestroyDate] IS NULL THEN 1 END) * 1.) / COUNT(*) AS [DestroyDate_PercNULL],
(COUNT(CASE WHEN [DestroyID] IS NULL THEN 1 END) * 1.) / COUNT(*) AS [DestroyID_PercNULL],
(COUNT(CASE WHEN [DestroyedBy] IS NULL THEN 1 END) * 1.) / COUNT(*) AS [DestroyedBy_PercNULL],
(COUNT(CASE WHEN [ValueExVAT] IS NULL THEN 1 END) * 1.) / COUNT(*) AS [ValueExVAT_PercNULL],
(COUNT(CASE WHEN [VATValue] IS NULL THEN 1 END) * 1.) / COUNT(*) AS [VATValue_PercNULL],
(COUNT(CASE WHEN [ValueIncVAT] IS NULL THEN 1 END) * 1.) / COUNT(*) AS [ValueIncVAT_PercNULL]
FROM [app].[Asset])
SELECT TOP(10) V.*
FROM Counts C
CROSS APPLY(VALUES(N'AssetID', C.[AssetID_PercNULL]),
(N'AssetName', C.[AssetName_PercNULL]),
(N'TypeID', C.[TypeID_PercNULL]),
(N'SerialNumber', C.[SerialNumber_PercNULL]),
(N'BarcodeNumber', C.[BarcodeNumber_PercNULL]),
(N'Manufacturer', C.[Manufacturer_PercNULL]),
(N'Model', C.[Model_PercNULL]),
(N'LocationID', C.[LocationID_PercNULL]),
(N'IPAddress', C.[IPAddress_PercNULL]),
(N'PurchaseDate', C.[PurchaseDate_PercNULL]),
(N'SetupDate', C.[SetupDate_PercNULL]),
(N'DecommissionDate', C.[DecommissionDate_PercNULL]),
(N'ReasonID', C.[ReasonID_PercNULL]),
(N'DecommissionBy', C.[DecommissionBy_PercNULL]),
(N'InvoiceID', C.[InvoiceID_PercNULL]),
(N'IsVirtual', C.[IsVirtual_PercNULL]),
(N'HostAssetID', C.[HostAssetID_PercNULL]),
(N'DestroyDate', C.[DestroyDate_PercNULL]),
(N'DestroyID', C.[DestroyID_PercNULL]),
(N'DestroyedBy', C.[DestroyedBy_PercNULL]),
(N'ValueExVAT', C.[ValueExVAT_PercNULL]),
(N'VATValue', C.[VATValue_PercNULL]),
(N'ValueIncVAT', C.[ValueIncVAT_PercNULL]))V(ColumnName,ColumnPercNULL)
ORDER BY V.ColumnPercNULL DESC;
This should give you some insight into how it works out the result.
Another way, using unpivot:
DECLARE #SCHEMANAME NVARCHAR(100) = 'dbo'
DECLARE #TABLENAME NVARCHAR(100) = 'your_table_name'
DECLARE #SQL NVARCHAR(MAX)
SELECT #SQL = 'SELECT TOP (10) * FROM (SELECT '+
STUFF (
(
SELECT ', CAST(SUM(CASE WHEN ' + Quotename(C.COLUMN_NAME) + ' IS NULL THEN 1 ELSE 0 END) * 100.00/COUNT(*) AS INT) AS ' + QUOTENAME(C.COLUMN_NAME, '"') + CHAR(13)
FROM INFORMATION_SCHEMA.COLUMNS C
WHERE TABLE_NAME = #TABLENAME
AND TABLE_SCHEMA = #SCHEMANAME
ORDER BY C.ORDINAL_POSITION
FOR XML PATH(''),type
).value('.', 'nvarchar(max)'),
1, 2, ''
)+' FROM '+QUOTENAME(#SCHEMANAME)+'.'+QUOTENAME(#TABLENAME)+') V1 UNPIVOT (NullsPerc FOR ColumnName IN ('+
STUFF (
(
SELECT ', '+ Quotename(C.COLUMN_NAME,'"') + CHAR(13)
FROM INFORMATION_SCHEMA.COLUMNS C
WHERE TABLE_NAME = #TABLENAME
AND TABLE_SCHEMA = #SCHEMANAME
ORDER BY C.ORDINAL_POSITION
FOR XML PATH(''),type
).value('.', 'nvarchar(max)'),
1, 2, ''
)+
')) AS UPVT
ORDER BY NULLSPERC DESC'
SELECT #SQL

Data File Size Stays Same Whereas Log File Size Is Increasing

I am using the following snippet to track the data and log file size increase after certain operations:
SELECT #SQL = STUFF((
SELECT '
USE [' + d.name + ']
INSERT INTO #space (database_id, data_used_size, log_used_size)
SELECT
DB_ID()
, SUM(CASE WHEN [type] = 0 THEN space_used END)
, SUM(CASE WHEN [type] = 1 THEN space_used END)
FROM (
SELECT s.[type], space_used = SUM(FILEPROPERTY(s.name, ''SpaceUsed'') * 8)
FROM sys.database_files s
GROUP BY s.[type]
) t;'
FROM sys.databases d
WHERE d.[state] = 0
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 2, '')
EXEC sys.sp_executesql #SQL
The problem is, after each write operation, log file size increases as expected but the data file size stays the same for 4 or five operations and then suddenly increases.
Why would this be?

what were the last few queries ran on SQL Server ?

what were the last few queries ran on SQL Server and with client name (system name) ?
i am running this query in server side
below query getting queries
SELECT deqs.last_execution_time AS [Time], dest.TEXT AS [Query]
FROM sys.dm_exec_query_stats AS deqs
CROSS APPLY sys.dm_exec_sql_text(deqs.sql_handle) AS dest
ORDER BY deqs.last_execution_time DESC
how can i get system name
for e.g
time | query | System Name
You could check the sp_who and sp_who2 text.
create procedure sys.sp_who2 --- 1995/11/03 10:16
#loginame sysname = NULL
as
set nocount on
declare
#retcode int
declare
#sidlow varbinary(85)
,#sidhigh varbinary(85)
,#sid1 varbinary(85)
,#spidlow int
,#spidhigh int
declare
#charMaxLenLoginName varchar(6)
,#charMaxLenDBName varchar(6)
,#charMaxLenCPUTime varchar(10)
,#charMaxLenDiskIO varchar(10)
,#charMaxLenHostName varchar(10)
,#charMaxLenProgramName varchar(10)
,#charMaxLenLastBatch varchar(10)
,#charMaxLenCommand varchar(10)
declare
#charsidlow varchar(85)
,#charsidhigh varchar(85)
,#charspidlow varchar(11)
,#charspidhigh varchar(11)
-- defaults
select #retcode = 0 -- 0=good ,1=bad.
select #sidlow = convert(varbinary(85), (replicate(char(0), 85)))
select #sidhigh = convert(varbinary(85), (replicate(char(1), 85)))
select
#spidlow = 0
,#spidhigh = 32767
--------------------------------------------------------------
IF (#loginame IS NULL) --Simple default to all LoginNames.
GOTO LABEL_17PARM1EDITED
-- select #sid1 = suser_sid(#loginame)
select #sid1 = null
if exists(select * from sys.syslogins where loginname = #loginame)
select #sid1 = sid from sys.syslogins where loginname = #loginame
IF (#sid1 IS NOT NULL) --Parm is a recognized login name.
begin
select #sidlow = suser_sid(#loginame)
,#sidhigh = suser_sid(#loginame)
GOTO LABEL_17PARM1EDITED
end
--------
IF (lower(#loginame collate Latin1_General_CI_AS) IN ('active')) --Special action, not sleeping.
begin
select #loginame = lower(#loginame collate Latin1_General_CI_AS)
GOTO LABEL_17PARM1EDITED
end
--------
IF (patindex ('%[^0-9]%' , isnull(#loginame,'z')) = 0) --Is a number.
begin
select
#spidlow = convert(int, #loginame)
,#spidhigh = convert(int, #loginame)
GOTO LABEL_17PARM1EDITED
end
--------
raiserror(15007,-1,-1,#loginame)
select #retcode = 1
GOTO LABEL_86RETURN
LABEL_17PARM1EDITED:
-------------------- Capture consistent sysprocesses. -------------------
select
spid
,status
,sid
,hostname
,program_name
,cmd
,cpu
,physical_io
,blocked
,dbid
,convert(sysname, rtrim(loginame))
as loginname
,spid as 'spid_sort'
, substring( convert(varchar,last_batch,111) ,6 ,5 ) + ' '
+ substring( convert(varchar,last_batch,113) ,13 ,8 )
as 'last_batch_char'
,request_id
into #tb1_sysprocesses
from sys.sysprocesses_ex with (nolock)
if ##error <> 0
begin
select #retcode = ##error
GOTO LABEL_86RETURN
end
--------Screen out any rows?
if (#loginame in ('active'))
delete #tb1_sysprocesses
where lower(status) = 'sleeping'
and upper(cmd) in (
'AWAITING COMMAND'
,'LAZY WRITER'
,'CHECKPOINT SLEEP'
)
and blocked = 0
--------Prepare to dynamically optimize column widths.
select
#charsidlow = convert(varchar(85),#sidlow)
,#charsidhigh = convert(varchar(85),#sidhigh)
,#charspidlow = convert(varchar,#spidlow)
,#charspidhigh = convert(varchar,#spidhigh)
select
#charMaxLenLoginName =
convert( varchar
,isnull( max( datalength(loginname)) ,5)
)
,#charMaxLenDBName =
convert( varchar
,isnull( max( datalength( rtrim(convert(varchar(128),db_name(dbid))))) ,6)
)
,#charMaxLenCPUTime =
convert( varchar
,isnull( max( datalength( rtrim(convert(varchar(128),cpu)))) ,7)
)
,#charMaxLenDiskIO =
convert( varchar
,isnull( max( datalength( rtrim(convert(varchar(128),physical_io)))) ,6)
)
,#charMaxLenCommand =
convert( varchar
,isnull( max( datalength( rtrim(convert(varchar(128),cmd)))) ,7)
)
,#charMaxLenHostName =
convert( varchar
,isnull( max( datalength( rtrim(convert(varchar(128),hostname)))) ,8)
)
,#charMaxLenProgramName =
convert( varchar
,isnull( max( datalength( rtrim(convert(varchar(128),program_name)))) ,11)
)
,#charMaxLenLastBatch =
convert( varchar
,isnull( max( datalength( rtrim(convert(varchar(128),last_batch_char)))) ,9)
)
from
#tb1_sysprocesses
where
spid >= #spidlow
and spid <= #spidhigh
--------Output the report.
EXEC(
'
SET nocount off
SELECT
SPID = convert(char(5),spid)
,Status =
CASE lower(status)
When ''sleeping'' Then lower(status)
Else upper(status)
END
,Login = substring(loginname,1,' + #charMaxLenLoginName + ')
,HostName =
CASE hostname
When Null Then '' .''
When '' '' Then '' .''
Else substring(hostname,1,' + #charMaxLenHostName + ')
END
,BlkBy =
CASE isnull(convert(char(5),blocked),''0'')
When ''0'' Then '' .''
Else isnull(convert(char(5),blocked),''0'')
END
,DBName = substring(case when dbid = 0 then null when dbid <> 0 then db_name(dbid) end,1,' + #charMaxLenDBName + ')
,Command = substring(cmd,1,' + #charMaxLenCommand + ')
,CPUTime = substring(convert(varchar,cpu),1,' + #charMaxLenCPUTime + ')
,DiskIO = substring(convert(varchar,physical_io),1,' + #charMaxLenDiskIO + ')
,LastBatch = substring(last_batch_char,1,' + #charMaxLenLastBatch + ')
,ProgramName = substring(program_name,1,' + #charMaxLenProgramName + ')
,SPID = convert(char(5),spid) --Handy extra for right-scrolling users.
,REQUESTID = convert(char(5),request_id)
from
#tb1_sysprocesses --Usually DB qualification is needed in exec().
where
spid >= ' + #charspidlow + '
and spid <= ' + #charspidhigh + '
-- (Seems always auto sorted.) order by spid_sort
SET nocount on
'
)
LABEL_86RETURN:
if (object_id('tempdb..#tb1_sysprocesses') is not null)
drop table #tb1_sysprocesses
return #retcode -- sp_who2
Hope this helps.
The below query should help you:
SELECT conn.session_id, sson.host_name, sson.login_name,
sqltxt.text, sson.login_time, sson.status
FROM sys.dm_exec_connections conn
INNER JOIN sys.dm_exec_sessions sson
ON conn.session_id = sson.session_id
CROSS APPLY sys.dm_exec_sql_text(most_recent_sql_handle) AS sqltxt
ORDER BY conn.session_id desc
Source: http://www.sqlservercurry.com/2011/12/last-run-query-in-sql-server.html

Find out complete SQL Server database size

I need to know how much space occupies all the databases inside an SQL Server 2000. I did some research but could not found any script to help me out.
Source: http://searchsqlserver.techtarget.com/tip/0,289483,sid87_gci1313431,00.html
Works with SQL2000,2005,2008
USE master;
GO
IF OBJECT_ID('dbo.sp_SDS', 'P') IS NOT NULL
DROP PROCEDURE dbo.sp_SDS;
GO
CREATE PROCEDURE dbo.sp_SDS
#TargetDatabase sysname = NULL, -- NULL: all dbs
#Level varchar(10) = 'Database', -- or "File"
#UpdateUsage bit = 0, -- default no update
#Unit char(2) = 'MB' -- Megabytes, Kilobytes or Gigabytes
AS
/**************************************************************************************************
**
** author: Richard Ding
** date: 4/8/2008
** usage: list db size AND path w/o SUMmary
** test code: sp_SDS -- default behavior
** sp_SDS 'maAster'
** sp_SDS NULL, NULL, 0
** sp_SDS NULL, 'file', 1, 'GB'
** sp_SDS 'Test_snapshot', 'Database', 1
** sp_SDS 'Test', 'File', 0, 'kb'
** sp_SDS 'pfaids', 'Database', 0, 'gb'
** sp_SDS 'tempdb', NULL, 1, 'kb'
**
**************************************************************************************************/
SET NOCOUNT ON;
IF #TargetDatabase IS NOT NULL AND DB_ID(#TargetDatabase) IS NULL
BEGIN
RAISERROR(15010, -1, -1, #TargetDatabase);
RETURN (-1)
END
IF OBJECT_ID('tempdb.dbo.##Tbl_CombinedInfo', 'U') IS NOT NULL
DROP TABLE dbo.##Tbl_CombinedInfo;
IF OBJECT_ID('tempdb.dbo.##Tbl_DbFileStats', 'U') IS NOT NULL
DROP TABLE dbo.##Tbl_DbFileStats;
IF OBJECT_ID('tempdb.dbo.##Tbl_ValidDbs', 'U') IS NOT NULL
DROP TABLE dbo.##Tbl_ValidDbs;
IF OBJECT_ID('tempdb.dbo.##Tbl_Logs', 'U') IS NOT NULL
DROP TABLE dbo.##Tbl_Logs;
CREATE TABLE dbo.##Tbl_CombinedInfo (
DatabaseName sysname NULL,
[type] VARCHAR(10) NULL,
LogicalName sysname NULL,
T dec(10, 2) NULL,
U dec(10, 2) NULL,
[U(%)] dec(5, 2) NULL,
F dec(10, 2) NULL,
[F(%)] dec(5, 2) NULL,
PhysicalName sysname NULL );
CREATE TABLE dbo.##Tbl_DbFileStats (
Id int identity,
DatabaseName sysname NULL,
FileId int NULL,
FileGroup int NULL,
TotalExtents bigint NULL,
UsedExtents bigint NULL,
Name sysname NULL,
FileName varchar(255) NULL );
CREATE TABLE dbo.##Tbl_ValidDbs (
Id int identity,
Dbname sysname NULL );
CREATE TABLE dbo.##Tbl_Logs (
DatabaseName sysname NULL,
LogSize dec (10, 2) NULL,
LogSpaceUsedPercent dec (5, 2) NULL,
Status int NULL );
DECLARE #Ver varchar(10),
#DatabaseName sysname,
#Ident_last int,
#String varchar(2000),
#BaseString varchar(2000);
SELECT #DatabaseName = '',
#Ident_last = 0,
#String = '',
#Ver = CASE WHEN ##VERSION LIKE '%9.0%' THEN 'SQL 2005'
WHEN ##VERSION LIKE '%8.0%' THEN 'SQL 2000'
WHEN ##VERSION LIKE '%10.0%' THEN 'SQL 2008'
END;
SELECT #BaseString =
' SELECT DB_NAME(), ' +
CASE WHEN #Ver = 'SQL 2000' THEN 'CASE WHEN status & 0x40 = 0x40 THEN ''Log'' ELSE ''Data'' END'
ELSE ' CASE type WHEN 0 THEN ''Data'' WHEN 1 THEN ''Log'' WHEN 4 THEN ''Full-text'' ELSE ''reserved'' END' END +
', name, ' +
CASE WHEN #Ver = 'SQL 2000' THEN 'filename' ELSE 'physical_name' END +
', size*8.0/1024.0 FROM ' +
CASE WHEN #Ver = 'SQL 2000' THEN 'sysfiles' ELSE 'sys.database_files' END +
' WHERE '
+ CASE WHEN #Ver = 'SQL 2000' THEN ' HAS_DBACCESS(DB_NAME()) = 1' ELSE 'state_desc = ''ONLINE''' END + '';
SELECT #String = 'INSERT INTO dbo.##Tbl_ValidDbs SELECT name FROM ' +
CASE WHEN #Ver = 'SQL 2000' THEN 'master.dbo.sysdatabases'
WHEN #Ver IN ('SQL 2005', 'SQL 2008') THEN 'master.sys.databases'
END + ' WHERE HAS_DBACCESS(name) = 1 ORDER BY name ASC';
EXEC (#String);
INSERT INTO dbo.##Tbl_Logs EXEC ('DBCC SQLPERF (LOGSPACE) WITH NO_INFOMSGS');
-- For data part
IF #TargetDatabase IS NOT NULL
BEGIN
SELECT #DatabaseName = #TargetDatabase;
IF #UpdateUsage <> 0 AND DATABASEPROPERTYEX (#DatabaseName,'Status') = 'ONLINE'
AND DATABASEPROPERTYEX (#DatabaseName, 'Updateability') <> 'READ_ONLY'
BEGIN
SELECT #String = 'USE [' + #DatabaseName + '] DBCC UPDATEUSAGE (0)';
PRINT '*** ' + #String + ' *** ';
EXEC (#String);
PRINT '';
END
SELECT #String = 'INSERT INTO dbo.##Tbl_CombinedInfo (DatabaseName, type, LogicalName, PhysicalName, T) ' + #BaseString;
INSERT INTO dbo.##Tbl_DbFileStats (FileId, FileGroup, TotalExtents, UsedExtents, Name, FileName)
EXEC ('USE [' + #DatabaseName + '] DBCC SHOWFILESTATS WITH NO_INFOMSGS');
EXEC ('USE [' + #DatabaseName + '] ' + #String);
UPDATE dbo.##Tbl_DbFileStats SET DatabaseName = #DatabaseName;
END
ELSE
BEGIN
WHILE 1 = 1
BEGIN
SELECT TOP 1 #DatabaseName = Dbname FROM dbo.##Tbl_ValidDbs WHERE Dbname > #DatabaseName ORDER BY Dbname ASC;
IF ##ROWCOUNT = 0
BREAK;
IF #UpdateUsage <> 0 AND DATABASEPROPERTYEX (#DatabaseName, 'Status') = 'ONLINE'
AND DATABASEPROPERTYEX (#DatabaseName, 'Updateability') <> 'READ_ONLY'
BEGIN
SELECT #String = 'DBCC UPDATEUSAGE (''' + #DatabaseName + ''') ';
PRINT '*** ' + #String + '*** ';
EXEC (#String);
PRINT '';
END
SELECT #Ident_last = ISNULL(MAX(Id), 0) FROM dbo.##Tbl_DbFileStats;
SELECT #String = 'INSERT INTO dbo.##Tbl_CombinedInfo (DatabaseName, type, LogicalName, PhysicalName, T) ' + #BaseString;
EXEC ('USE [' + #DatabaseName + '] ' + #String);
INSERT INTO dbo.##Tbl_DbFileStats (FileId, FileGroup, TotalExtents, UsedExtents, Name, FileName)
EXEC ('USE [' + #DatabaseName + '] DBCC SHOWFILESTATS WITH NO_INFOMSGS');
UPDATE dbo.##Tbl_DbFileStats SET DatabaseName = #DatabaseName WHERE Id BETWEEN #Ident_last + 1 AND ##IDENTITY;
END
END
-- set used size for data files, do not change total obtained from sys.database_files as it has for log files
UPDATE dbo.##Tbl_CombinedInfo
SET U = s.UsedExtents*8*8/1024.0
FROM dbo.##Tbl_CombinedInfo t JOIN dbo.##Tbl_DbFileStats s
ON t.LogicalName = s.Name AND s.DatabaseName = t.DatabaseName;
-- set used size and % values for log files:
UPDATE dbo.##Tbl_CombinedInfo
SET [U(%)] = LogSpaceUsedPercent,
U = T * LogSpaceUsedPercent/100.0
FROM dbo.##Tbl_CombinedInfo t JOIN dbo.##Tbl_Logs l
ON l.DatabaseName = t.DatabaseName
WHERE t.type = 'Log';
UPDATE dbo.##Tbl_CombinedInfo SET F = T - U, [U(%)] = U*100.0/T;
UPDATE dbo.##Tbl_CombinedInfo SET [F(%)] = F*100.0/T;
IF UPPER(ISNULL(#Level, 'DATABASE')) = 'FILE'
BEGIN
IF #Unit = 'KB'
UPDATE dbo.##Tbl_CombinedInfo
SET T = T * 1024, U = U * 1024, F = F * 1024;
IF #Unit = 'GB'
UPDATE dbo.##Tbl_CombinedInfo
SET T = T / 1024, U = U / 1024, F = F / 1024;
SELECT DatabaseName AS 'Database',
type AS 'Type',
LogicalName,
T AS 'Total',
U AS 'Used',
[U(%)] AS 'Used (%)',
F AS 'Free',
[F(%)] AS 'Free (%)',
PhysicalName
FROM dbo.##Tbl_CombinedInfo
WHERE DatabaseName LIKE ISNULL(#TargetDatabase, '%')
ORDER BY DatabaseName ASC, type ASC;
SELECT CASE WHEN #Unit = 'GB' THEN 'GB' WHEN #Unit = 'KB' THEN 'KB' ELSE 'MB' END AS 'SUM',
SUM (T) AS 'TOTAL', SUM (U) AS 'USED', SUM (F) AS 'FREE' FROM dbo.##Tbl_CombinedInfo;
END
IF UPPER(ISNULL(#Level, 'DATABASE')) = 'DATABASE'
BEGIN
DECLARE #Tbl_Final TABLE (
DatabaseName sysname NULL,
TOTAL dec (10, 2),
[=] char(1),
used dec (10, 2),
[used (%)] dec (5, 2),
[+] char(1),
free dec (10, 2),
[free (%)] dec (5, 2),
[==] char(2),
Data dec (10, 2),
Data_Used dec (10, 2),
[Data_Used (%)] dec (5, 2),
Data_Free dec (10, 2),
[Data_Free (%)] dec (5, 2),
[++] char(2),
Log dec (10, 2),
Log_Used dec (10, 2),
[Log_Used (%)] dec (5, 2),
Log_Free dec (10, 2),
[Log_Free (%)] dec (5, 2) );
INSERT INTO #Tbl_Final
SELECT x.DatabaseName,
x.Data + y.Log AS 'TOTAL',
'=' AS '=',
x.Data_Used + y.Log_Used AS 'U',
(x.Data_Used + y.Log_Used)*100.0 / (x.Data + y.Log) AS 'U(%)',
'+' AS '+',
x.Data_Free + y.Log_Free AS 'F',
(x.Data_Free + y.Log_Free)*100.0 / (x.Data + y.Log) AS 'F(%)',
'==' AS '==',
x.Data,
x.Data_Used,
x.Data_Used*100/x.Data AS 'D_U(%)',
x.Data_Free,
x.Data_Free*100/x.Data AS 'D_F(%)',
'++' AS '++',
y.Log,
y.Log_Used,
y.Log_Used*100/y.Log AS 'L_U(%)',
y.Log_Free,
y.Log_Free*100/y.Log AS 'L_F(%)'
FROM
( SELECT d.DatabaseName,
SUM(d.T) AS 'Data',
SUM(d.U) AS 'Data_Used',
SUM(d.F) AS 'Data_Free'
FROM dbo.##Tbl_CombinedInfo d WHERE d.type = 'Data' GROUP BY d.DatabaseName ) AS x
JOIN
( SELECT l.DatabaseName,
SUM(l.T) AS 'Log',
SUM(l.U) AS 'Log_Used',
SUM(l.F) AS 'Log_Free'
FROM dbo.##Tbl_CombinedInfo l WHERE l.type = 'Log' GROUP BY l.DatabaseName ) AS y
ON x.DatabaseName = y.DatabaseName;
IF #Unit = 'KB'
UPDATE #Tbl_Final SET TOTAL = TOTAL * 1024,
used = used * 1024,
free = free * 1024,
Data = Data * 1024,
Data_Used = Data_Used * 1024,
Data_Free = Data_Free * 1024,
Log = Log * 1024,
Log_Used = Log_Used * 1024,
Log_Free = Log_Free * 1024;
IF #Unit = 'GB'
UPDATE #Tbl_Final SET TOTAL = TOTAL / 1024,
used = used / 1024,
free = free / 1024,
Data = Data / 1024,
Data_Used = Data_Used / 1024,
Data_Free = Data_Free / 1024,
Log = Log / 1024,
Log_Used = Log_Used / 1024,
Log_Free = Log_Free / 1024;
DECLARE #GrantTotal dec(11, 2);
SELECT #GrantTotal = SUM(TOTAL) FROM #Tbl_Final;
SELECT
CONVERT(dec(10, 2), TOTAL*100.0/#GrantTotal) AS 'WEIGHT (%)',
DatabaseName AS 'DATABASE',
CONVERT(VARCHAR(12), used) + ' (' + CONVERT(VARCHAR(12), [used (%)]) + ' %)' AS 'USED (%)',
[+],
CONVERT(VARCHAR(12), free) + ' (' + CONVERT(VARCHAR(12), [free (%)]) + ' %)' AS 'FREE (%)',
[=],
TOTAL,
[=],
CONVERT(VARCHAR(12), Data) + ' (' + CONVERT(VARCHAR(12), Data_Used) + ', ' +
CONVERT(VARCHAR(12), [Data_Used (%)]) + '%)' AS 'DATA (used, %)',
[+],
CONVERT(VARCHAR(12), Log) + ' (' + CONVERT(VARCHAR(12), Log_Used) + ', ' +
CONVERT(VARCHAR(12), [Log_Used (%)]) + '%)' AS 'LOG (used, %)'
FROM #Tbl_Final
WHERE DatabaseName LIKE ISNULL(#TargetDatabase, '%')
ORDER BY DatabaseName ASC;
IF #TargetDatabase IS NULL
SELECT CASE WHEN #Unit = 'GB' THEN 'GB' WHEN #Unit = 'KB' THEN 'KB' ELSE 'MB' END AS 'SUM',
SUM (used) AS 'USED',
SUM (free) AS 'FREE',
SUM (TOTAL) AS 'TOTAL',
SUM (Data) AS 'DATA',
SUM (Log) AS 'LOG'
FROM #Tbl_Final;
END
RETURN (0)
GO
I know this might sound a little arcanine but why not just stat the directory that contains the database.
if you use SQL Server Management Studio (from SQL 2005 or newer) you can just right-click properties on the database itself, and then click on the storage tab.

Resources