2

is there a function to convert datetime to bigint in sql? E.g. I have a date "2010-11-02 00:00:00" and i would like to get result as number "20101102000000"

Or do I need to write some custom function which will remove -,space,: from datetime?

pramodtech
  • 6,300
  • 18
  • 72
  • 111
  • That doesn't really make sense. You mean you want it as a string. Formatted like: "yyyyMMddHHmmss"? - Just out of interest, why do you need it as a big int? – Lee Gunn May 10 '11 at 12:22
  • @Lee Gunn - not necessarily, you could decide to store your dates as "integers" and assume the "format" of the number, i.e. to way to interpret it, to be like yyyyMMddHHmmss. That is the last to digits are the seconds, the next two are the minutes, etc. – Christian.K May 10 '11 at 12:34
  • but a date is already a big int...it's the number of ticks (or whatever) since the epoch. – Lee Gunn May 10 '11 at 12:36

4 Answers4

3

you can try this code here..

update Table_1 set xnew=REPLACE(REPLACE(REPLACE (CONVERT(VARCHAR,x,20) , '-' , '' ),':',''),' ','')

but this is duplicate question I answered it here too : Sql datatype conversion

Community
  • 1
  • 1
Adnan M. TURKEN
  • 1,554
  • 4
  • 21
  • 36
1

The solution I have been using lately (in SQL 2008 R2) is:

cast(CONVERT(nvarchar(8),CURRENT_TIMESTAMP,112) as bigint)

The number of characters in the nvarchar limits the precision. I only need the date.

1

You cannot convert '2010-11-02 00:00:00' to 20101102000000 in T-SQL directly so yes, as you say, you would need to modify the string into something you can cast as a bigint.

declare @str varchar(19) = '2010-11-02 00:00:00'
select cast(replace(replace(replace(@str, '-', ''), ' ', ''), ':', '') as bigint)
Alex K.
  • 171,639
  • 30
  • 264
  • 288
0

Here is a solution:

declare @t datetime = '2010-11-02 00:00:00'

select  DATEPART(second, @t) +
        DATEPART(minute, @t) * 100 +
        DATEPART(hour, @t) * 10000 +
        DATEPART(day, @t) * 1000000 +
        DATEPART(month, @t) * 100000000 +
        DATEPART(year, @t) * 10000000000
Johan
  • 1,152
  • 7
  • 16