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.