Here is my question:
This is a table named HB06,the data type of "WRTime" is datatime.I want to convert all WRTime to int. For example 2012-11-09 10:52:38.000
will be converted to 20121109105238
.
Thank you!
Here is my question:
This is a table named HB06,the data type of "WRTime" is datatime.I want to convert all WRTime to int. For example 2012-11-09 10:52:38.000
will be converted to 20121109105238
.
Thank you!
You can't. The value is too large for the int data type. But it does fit into a bigint.
What you can do is to convert it to a string with the desired format, and then cast that ti the bigint type. Using the FORMAT function is IMO more straight forward:
DECLARE @a datetime = '20120304 23:34:12'
SELECT @a
SELECT CAST(FORMAT(@a, 'yyyyMMddhhmmss') AS bigint)
The alternative is to use CONVERT function, which uses less CPU. But there's not direct style that matches that format, so you would then REPLACE() various "litter" characters with nothing. I wouldn't bother with the CONVERT() option unless you work over large data sets.
You can try with below one
select concat(convert(varchar,WRTime,112),datepart(HH,WRTime),
datepart(MINUTE,WRTime),datepart(SS,WRTime)) from HB06
select
cast(replace(replace(replace(convert(varchar(19), WRTime, 121),':',''),'-',''),' ','') as bigint)
FROM HB06
Use below Convert function:
SELECT CONVERT(VARCHAR(100),WRTime,112)+REPLACE(CONVERT(VARCHAR(100),WRTime,108),':','')
FROM HB06
SQL Version 2012 or higher you can use the FORMAT function to get just year and month, then cast it as an int.
On versions prior to 2012 you can do the formatting with the convert function, then cast as int.
declare @WRTime datetime
set @WRTime = '2012-11-09 10:52:38.000'
select cast(format(@WRTime,'yyyyMM') as int) --2012 or higher
OR You can use:
SELECT YEAR(@WRTime)*100 + MONTH(@WRTime);
2012-11-09 10:52:38.000 will be converted to 20121109105238??
Int can't convert this so use "BIGINT"
declare @WRTime datetime
set @WRTime = '2012-11-09 10:52:38.000'
select cast(format(@WRTime,'yyyyMMddHHmmssfff') as bigint) --2012 or higher