简体   繁体   English

sql中从INT到varchar的转换

[英]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我有一个表,其中有像 20170730 这样的值,还有 0 个值为 INT 类型的值

I am trying to convert it to value like 30/07/2017, for which i am using the below code,我正在尝试将其转换为 30/07/2017 之类的值,为此我使用了以下代码,

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,我的要求是在有日期值时进行转换,如果有 0 那么它应该是零,如下所示,

Result 
30/07/2017
0

Can u pls help你能帮忙吗

As already pointed out in the comments, you can try to use a CASE expression正如评论中已经指出的那样,您可以尝试使用CASE表达式

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() .try_convert()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.后者还将纠正其他“格式错误”的数据,例如123 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.将列的数据类型更改为某种日期/时间数据类型真正解决此问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM