pstakashi pstakashi - 27 days ago 6
SQL Question

TSQL Cursor automatically rounds up money type variables

I don't know why this code output 0.34 (I expected 0.335).
Does TSQL cursor automatically round up money type variables?
Please help me who knows about this.

DECLARE @Rate MONEY;

DECLARE csrRate
CURSOR FOR
SELECT 0.335

OPEN csrRate;
FETCH NEXT FROM
csrRate
INTO
@Rate

WHILE @@FETCH_STATUS = 0
BEGIN
PRINT @Rate

FETCH NEXT FROM csrRate INTO @Rate
END
CLOSE csrRate
DEALLOCATE csrRate

Answer

This is the default behavior when PRINT is used. It cast the money to string. And the default is:

enter image description here

So, you can cast it like this:

DECLARE @Rate MONEY;

DECLARE csrRate
CURSOR FOR
    SELECT $0.335

OPEN csrRate;
FETCH NEXT FROM
    csrRate
INTO
    @Rate

    WHILE @@FETCH_STATUS = 0
    BEGIN

        PRINT @Rate
        PRINT convert(varchar(30), @Rate, 2)
        --SELECT @RATE


        FETCH NEXT FROM csrRate INTO @Rate
    END
CLOSE csrRate
DEALLOCATE csrRate

Also, if you try to SELECT the value, it is not cast to string.

Comments