Programing

SQL Server, 나누기는 0을 반환합니다.

lottogame 2020. 10. 21. 07:36
반응형

SQL Server, 나누기는 0을 반환합니다.


예제에서 사용중인 코드는 다음과 같습니다.

 PRINT @set1
 PRINT @set2

 SET @weight= @set1 / @set2;
 PRINT @weight

결과는 다음과 같습니다.

47
638
0

0대신 왜 돌아 오는지 알고 싶습니다.0,073667712


set1 및 set2를 정수 대신 부동 소수점으로 선언하거나 계산의 일부로 부동 소수점으로 캐스팅합니다.

SET @weight= CAST(@set1 AS float) / CAST(@set2 AS float);

나눗셈에서 정수만 사용하면 정수 나눗셈을 얻게됩니다. (적어도 하나의) double 또는 float를 사용하면 부동 소수점 나누기 (그리고 원하는 답)를 얻을 수 있습니다.

그래서 당신은 할 수 있습니다

  1. 변수 중 하나 또는 모두를 float / double로 선언
  2. 변수 중 하나 또는 둘 모두를 float / double로 캐스팅합니다.

정수 나눗셈의 결과를 두 배로 캐스트하지 마십시오. 나눗셈은 이미 정수 나눗셈으로 수행되었으므로 소수 뒤의 숫자는 이미 손실되었습니다.


정수이기 때문입니다. 이를 부동 소수점 숫자 또는 소수로 선언하거나 계산에서 이와 같이 캐스트해야합니다.


나누기의 하단을 1.0 (또는 원하는만큼 소수점 이하 자릿수)으로 간단히

PRINT @set1 
PRINT @set2 
SET @weight= @set1 / @set2 *1.00000; 
PRINT @weight

float 또는 10 진수 형식으로 선언하면 표시됩니다.

0

예 :

declare @weight float;

SET @weight= 47 / 638; PRINT @weight

출력 : 0

출력을 원하는 경우

0.073667712

declare @weight float;

SET @weight= 47.000000000 / 638.000000000; PRINT @weight

SQL Server에서 두 정수의 직접 나누기는 결과가 부동 소수점이어야하는 경우에도 정수를 반환합니다. 아래의 예가 있습니다.

--1--
declare @weird_number_float float
set @weird_number_float=22/7
select @weird_number_float

--2--
declare @weird_number_decimal decimal(18,10)
set @weird_number_decimal=22/7 
select @weird_number_decimal

--3--
declare @weird_number_numeric numeric
set @weird_number_numeric=22/7 
select @weird_number_numeric

--Right way

declare @weird_number float
set @weird_number=cast(22 as float)/cast(7 as float)
select @weird_number

마지막 블록은 3,14285714285714를 반환합니다. 올바른 정밀도로 정의 된 두 번째 블록에도 불구하고 결과는 3.00000이됩니다.

참고 URL : https://stackoverflow.com/questions/1666407/sql-server-division-returns-zero

반응형