TeradataTip1 – Casting decimal(n) to varchar without extra characters

To convert a decimal(n) value to a simple string containing only digits, use this:

SELECT
  cast( cast( d AS format 'Z(I)' ) AS varchar(30) )
FROM T;

Why do you need the double cast? Well, if you try to convert from a column that has a decimal(n) to a numeric string and you simply cast to a varchar, Teradata will add a decimal point at the end of your string.

CREATE TABLE T(d decimal(18));
INSERT INTO T VALUES(42);
INSERT INTO T VALUES(3);
 
SELECT '['||cast(d AS varchar(20))||']' FROM T;
(('['||d)||']')
----------------------
[3.]
[42.]
SELECT
  '['||cast(cast(d AS format 'Z(I)') AS varchar(20)) ||']'
FROM T;
(('['||d)||']')
----------------------
[3]
[42]

Tags:

Leave a Reply

You must be logged in to post a comment.