2016-08-13 15 views
1

嗨我寫一個程序轉換一個整數爲十進制,但每當我執行過程我得到這個錯誤:轉換int在程序十進制

Msg 8115, Level 16, State 8, Procedure gradesInsert, Line 9
Arithmetic overflow error converting numeric to data type numeric.

Msg 8115, Level 16, State 8, Procedure gradesInsert, Line 10
Arithmetic overflow error converting numeric to data type numeric.

這是我創建的表。

CREATE TABLE French 
(
     StudentId int Primary key, 
     StudentName varchar(75), 
     Class varchar (15), 
     SubjectName varchar(25) DEFAULT ('Mathematics'), 
     FirstPeriod int, 
     SecondPeriod int, 
     ThirdPeriod int, 
     FirstSemesterExam int, 
     FirstSemesterAvg decimal(2,2), 
     FourthPeriod int, 
     FifthPeriod int, 
     SixPeriod int, 
     SecondSemesterExam int, 
     SecondSemesterAvg decimal(2,2) 
) 

這是程序以及它的調用方式。

create proc gradesInsert 
    @StuId int, @p1 int, @p2 int, @p3 int, @firstExam int, 
    @p4 int, @p5 int, @p6 int, @SecondExam int 
As 
    declare @add1 int = @p1 + @p2 + @p3 + @firstExam 
    declare @add2 int = @p4 + @p2 + @p6 + @SecondExam 

    declare @firstAvg decimal(2,2) = cast(@add1/4.0 as decimal(2,2)) 
    declare @SecondAvg decimal(2,2) = cast(@add2/4.0 as decimal(2,2)) 
begin 
    update dbo.French 
    Set FirstPeriod = @p1, 
     SecondPeriod = @p2, 
     ThirdPeriod = @p3, 
     FourthPeriod [email protected], 
     FirstSemesterExam = @firstExam, 
     FirstSemesterAvg = @firstAvg, 
     FifthPeriod = @p5, 
     SixPeriod = @p6, 
     SecondSemesterExam = @SecondExam, 
     SecondSemesterAvg = @SecondAvg 
    where 
     dbo.French.StudentId = @StuId 
end 



Exec gradesInsert 1, 90, 98, 77, 69, 70, 72, 99, 100 

我想要的學生平均有兩個數字點和規模兩個地方小數點像前(99.43)的右左。

我不知道我在這裏失蹤的傢伙,但我會感激你的誠實意見和反饋。

謝謝你們!

回答

5

在SQL Server DECIMAL列的定義定義爲:

DECIMAL(precision, scale) 

其中precision代表的的位數,和scale爲的小數點後的位數。

所以decimal(2,2)指:a 總2的位數,它們的2 小數點後。

通過此聲明,您基本上只能將.00.99中的值存儲在該列中。那真的是你想要什麼?

閱讀所有關於decimal and numeric types細節在MSDN上的SQL Server .....

+0

感謝您的鏈接 –

0

我找到了一種方法來解決它。似乎要在右邊有兩個地方的十進制數字,在左邊有兩個或多個地方的十進制數字;您必須設置精度爲五(5)和二(2)的小數位數。例如, myNmber十進制(5,2)

記住從精度值中減去比例值。因此,在上面的示例中,從精度值5(5)中減去2(2)的比例值得出的值爲3(3),該值可以保存左側的任意三(3)位數字。這適用於分紅是三位數字的分割。

如果你想做一個分紅,其中股息是四(4)位數字,那麼你的領域應該看起來像這樣。防爆。 myNumber小數(6,2)。

所以,在我的情況下我不得不這樣做是爲了重新在我桌上的東西如下:

FirstSemesterAvg decimal(6,2), 
SecondSemesterAvg decimal(6,2), 

並以我的程序:

declare @firstAvg decimal(6,2) = cast(@add1 as decimal(6,2))/4 
declare @SecondAvg decimal(6,2) = cast(@add2 as decimal(6,2))/4 

它工作正常的傢伙。