SQL Server convert datetime field to int in sql

cbjzeqam  于 2023-04-28  发布在  其他
关注(0)|答案(3)|浏览(117)

my date column value looks like:

2023-04-23 00:00:00
2023-04-23 00:50:00
''
NULL

I want to convert it to

20230423000000
20230423005000
''
NULL

When I used

Select FORMAT (DAT,'yyyyMMddHHmmss' from table give error as
Argument datatype nvarchar is invalid for argument 1 of format function.
kadbb459

kadbb4591#

You couldn't use FORMAT because datatype filed date is nvarchar

first you must cast with datetime and you must check empty and null field dates

Select case when dates='' or dates is null then ''
else FORMAT (try_cast( dates as datetime),'yyyyMMddHHmmss') end from Da

You can insert Base data with the following statements:

drop table Da
create table Da(dates nvarchar(100)  )
insert into Da (dates) values('2023-04-23 00:00:00')
insert into Da (dates) values('2023-04-23 00:50:00')
insert into Da (dates) values('')
insert into Da (dates) values(null)
8iwquhpp

8iwquhpp2#

From the error message, your column is of a string-like datatype, not datetime-like. If so, you probably want to use string functions:

select 
    concat(
        substring(dat, 1, 4), 
        substring(dat, 6, 2),
        substring(dat, 9, 2),
        substring(dat, 12, 2),
        substring(dat, 15, 2),
        substring(dat, 18, 2)
    ) as new_dat
from mytable

Or using replace() multiple times:

select replace(replace(replace(dat, ' ', ''); ':' ''), '-', '') as new_dat
from mytable
kdfy810k

kdfy810k3#

The integer value returned in this conversion refers to the number of days since Jan 01, 1900. In your second query, the date you have entered is stored as a varchar, thus the conversion error you're seeing. You can cast or convert this to a datetime and the query will succeed.

Ex:

SELECT CONVERT(INT, CONVERT(DATETIME,'2013-08-05 09:23:30'))
SELECT CONVERT(INT, CAST ('2013-08-05 09:23:30' as DATETIME))

相关问题