Pregunta

The DateDiff = 23 so 23/30 is 0.77.

I cannot get @Tenor to be 1, which is 0.77 rounded ... it keeps giving me 0 ...

DECLARE @Tenor Decimal(18,6)
SET     @Tenor =  ROUND(DATEDIFF(D,'2014-04-14','2014-05-07') / 30, 0)

It works if I do this ... this will give me 1. But I need to use the method above because it's all in an UPDATE statement. Tips appreciated, thanks.

DECLARE @Tenor Decimal(18,6)
DECLARE @dd decimal(18, 6)
SELECT @dd = DATEDIFF(D, '2014-04-14', '2014-05-07') 
SET @Tenor = Round(@dd/30,0)
¿Fue útil?

Solución

Use 30.0 in your division to force non-integer arithmetic

DECLARE @Tenor Decimal(18,6)
SET     @Tenor =  ROUND(DATEDIFF(D,'2014-04-14','2014-05-07') / 30.0, 0)
SELECT  @Tenor -- 1.000000

The behaviour you are seeing is as a result of implicit type conversion in SQL Server. Both the return type of DATEDIFF(D,'2014-04-14','2014-05-07') and 30 are int, so integer division will occur when dividing the two (effectively removing the fractional part of the result, i.e. 0).

In your second attempt the dividend (@dd) is defined as decimal which results an implicit cast of the divisor (30) to decimal, giving the result you'd expect.

Otros consejos

SELECT @Tenor =  ROUND((CAST(DATEDIFF(D,'2014-04-14','2014-05-07') AS DECIMAL(18,6)) / 30), 0)

This should work to round it to 1.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top