cancel
Showing results for 
Search instead for 
Did you mean: 

Cast to DECIMAL with a variable scale

0 Kudos
1,762

Here is a simple example:

BEGIN
   DECLARE three INTEGER;
   SET three = 3;

   -- Working
   SELECT CAST(32.3369 as DECIMAL(30, 3));

   -- Not working
   --SELECT CAST(32.3369 as DECIMAL(30, three));
END

Is there a way to cast a decimal to a variable scale?

Business case: Some currency amounts are rounded to 3 decimals in some cultures, others to 2.

Accepted Solutions (1)

Accepted Solutions (1)

BEGIN
   DECLARE three INTEGER;
   SET three = 3;

   -- Working
   SELECT CAST(32.3369 as DECIMAL(30, 3));

   -- Working :)
   SELECT Round(32.3369, three), Truncnum(32.3369, three) ;
END
0 Kudos

Great! Thank you.

Answers (1)

Answers (1)

VolkerBarth
Contributor

EXECUTE IMMEDIATE is your friend here if you want to use CAST with a DECIMAL and a variable scale.

BEGIN
   DECLARE three INTEGER;
   SET three = 3;

   -- Working
   SELECT CAST(32.3369 as DECIMAL(30, 3));

   -- Now working
   EXECUTE IMMEDIATE 'SELECT CAST(32.3369 as DECIMAL(30, ' || three || '))';
END

For ROUND(), Dmitri's approach is strongly recommended...

0 Kudos

Good tip on using EXECUTE IMMEDIATE. Thanks!