Question

I try to create a table to store the used storage Information for every Database.
Since theese are hosted on different Cluster / Instances, I created a table with all Instance / Server Information.
_________________________
|________DBInstance_______|
|____ID___|_Instance_______|
|____1____|Server\Instance__|
|____2____|AG-Listener_____|

I then create a cursor and send my query to every server listed in the Instance-Table.

DECLARE @ID nvarchar(2), @Instancename VARCHAR(50), @cmd NVARCHAR(MAX)
DECLARE DBCursor CURSOR FOR 
SELECT ID, Instance 
from DBInstancelist; 

DECLARE @ID nvarchar(2), @Instancename VARCHAR(50), @cmd NVARCHAR(MAX)
DECLARE DBCursor CURSOR FOR 
SELECT ID, Instance 
from DBInstancelist; 

OPEN DBCursor 
FETCH NEXT FROM DBCursor into @id , @Instancename
WHILE @@FETCH_STATUS = 0 
BEGIN
select @cmd = N'INSERT INTO DBSIZE 
select a.*
from OPENROWSET (''SQLNCLI'',''Server=' + @Instancename + ';Trusted_Connection=YES;'',''select 
        [ID] = '+@ID+',
        [Database Name] = DB_NAME(database_id),
        [Type] = CASE WHEN Type_Desc = ''''ROWS'''' THEN ''''Data File''''
                      WHEN Type_Desc = ''''LOG''''  THEN ''''Log File''''
                      ELSE ''''SUMME'''' END,
        [Size in MB] = CAST( ((SUM(Size)* 8) / 1024.0) AS DECIMAL ),
        GETDATE() AS Scantime
FROM   sys.master_files
WHERE      database_id > 4
GROUP BY      GROUPING SETS
              (
                     (DB_NAME(database_id), Type_Desc),
                     (DB_NAME(database_id))
              )
ORDER BY      DB_NAME(database_id), Type_Desc DESC'') 
AS a;'
--select @cmd
exec sp_executesql @cmd
--select @cmd
FETCH NEXT FROM DBCursor into @ID, @Instancename
END 
CLOSE DBCursor
DEALLOCATE DBCursor

for the first 4 Instances I receive the Information I except, for the 5th Instance however, I reveice following Error.

 "Arithmetic overflow error converting expression to data type int.


This error only Appears, If I add the Line

 "[ID] = '+@ID+',",

but the ID of the Instance is needed for further Reporting.

Why is the converting appearing, and how can I stop it (Where is my mistake)?

Was it helpful?

Solution

Sorry, don't know how to highlight a comment.

Scott Hodgin postet the solution:

[Size in MB] = CAST( ((SUM(cast(Size as bigint))* 8) / 1024.0)as decimal),



is the correct line, and solution to my problem:)
Thank you very much:) !

Licensed under: CC-BY-SA with attribution
Not affiliated with dba.stackexchange
scroll top