Cursors

Openrowset中變數的算術溢出

  • November 15, 2018

我嘗試創建一個表來儲存每個數據庫使用的儲存資訊。

由於這些託管在不同的集群/實例上,我創建了一個包含所有實例/伺服器資訊的表。


|_DBInstance|

|ID|實例_____|

|1|伺服器\實例__|

|2|AG-聽眾_____|

然後我創建一個游標並將我的查詢發送到 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

對於前 4 個實例,我收到了我的資訊,但對於第 5 個實例,我收到了以下錯誤。

"Arithmetic overflow error converting expression to data type int.

僅出現此錯誤,如果我添加行

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

但進一步報告需要實例的 ID。

為什麼會出現轉換,我該如何阻止它(我的錯誤在哪裡)?

抱歉,不知道如何突出顯示評論。

Scott Hodgin 提出解決方案:

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

是正確的路線,並解決了我的問題:)

非常感謝:)!

引用自:https://dba.stackexchange.com/questions/222628