Sandip Das
Sandip Das

Reputation: 13

Conversion from INT to varchar in sql

I have a table where there are values like 20170730 and also 0 values are there which is INT type

I am trying to convert it to value like 30/07/2017, for which i am using the below code,

Select convert(NVARCHAR(10),convert(date,convert(NCHAR(8),datecolumn)),103) from table

But for the zero values i am getting the below error Conversion failed when converting date and/or time from character string. If i delete all the zero this working fine but problem having with zero.

My requirement is to convert when there a date value and if 0 are there then it should be zero only like below,

Result 
30/07/2017
0

Can u pls help

Upvotes: 0

Views: 2156

Answers (1)

sticky bit
sticky bit

Reputation: 37487

As already pointed out in the comments, you can try to use a CASE expression

SELECT CASE
         WHEN nmuloc = 0 THEN
           '0'
         ELSE
           convert(varchar(10),
                   convert(date,
                           convert(varchar(8),
                                   nmuloc),
                           112),
                   103)
       END
       FROM elbat;

or try_convert() and coalesce().

SELECT coalesce(convert(varchar(10),
                        try_convert(date,
                                    convert(varchar(8),
                                            nmuloc),
                                    112),
                       103),
                '0')
       FROM elbat;

db<>fiddle

The latter one will also correct other "malformed" data like 123 for example. The former will also fail in such cases. You may want that or not.

But, as also already pointed out in the comments, your real problem is that you use an inappropriate data type. Change the column's datatype to some date/time data type to really fix this.

Upvotes: 2

Related Questions