2015-06-07 42 views
2

我有這個疑問:SQL:左連接和金額:算術溢出錯誤將表達式轉換爲數據類型爲int

select p.UserName, sum(b.PercentRials) as amount, sum(r.Amount) as Pays 
from bills b inner join UserProfiles p on b.PayerUserName=p.UserName 
left outer join PayReceipts r on p.UserName=r.UserName 
where p.[Percent]>0 and b.PayDate>'2014-11-20' 
group by p.UserName 

我得到這個錯誤,運行時:

Msg 8115, Level 16, State 2, Line 1 
Arithmetic overflow error converting expression to data type int. 
Warning: Null value is eliminated by an aggregate or other SET operation. 

我能理解外連接導致此錯誤,因爲當我刪除最後一筆總和時,它運行正常。但我記得做了這樣的查詢,得到NULL在外連接表上求和。

我該怎麼辦?

回答

2

嘗試表達在SUM

select p.UserName, sum(b.PercentRials) as amount, sum(CAST (r.Amount AS BIGINT)) as Pays 
from bills b inner join UserProfiles p on b.PayerUserName=p.UserName 
left outer join PayReceipts r on p.UserName=r.UserName 
where p.[Percent]>0 and b.PayDate>'2014-11-20' 
group by p.UserName 

類型確定輸出的類型。所以當你的總和超過整數限制時,你會收到這個錯誤。爲了將您的數據視爲整數而不會出現錯誤,您需要castamount列爲BIGINT,因此總和將是BIGINT類型。

+0

警告誤導我。我認爲外部連接是原因,我預計「支付」列值要小得多。謝謝。 – Mahmoodvcs

2

如果你在一家金融公司工作,

sum(r.Amount) as Pays 

很可能會溢出兩個十億微薄的整數限制。你可以轉換爲一個較大的變量類型,like a decimal

sum(cast(r.Amount as decimal(38,2))) as Pays 
相關問題