Question

Ok this is how stupidly i am keeping my date as string

23.12.2012 21:24:31

Now at a select query i want to cast them as BigInt and do a search

casted version : "20121223212431"

like below

select * from myTable where cast(datestring as bigint) > 20111223212431 

How can i cast that kind of string to BigInt at sql server ?

Edit - why this query is not working

    select (convert(datetime,LastMoveTime,104)) as myTime from myTable
where myTime < DATEADD(day,-366,GETDATE())

error : Invalid column name 'myTime'.

Was it helpful?

Solution 2

You should not do that, see John Skeet's post, but

declare @dt datetime
select @dt='20121223 21:24:31'

Select Cast(Convert(Varchar(25),@dt,112)+Replace(Convert(Varchar(25),@dt,108),':','') as BigInt)

OTHER TIPS

Firstly, it would be best to just fix the schema to use DATETIME instead.

If you can't do that, you can use a CONVERT expression to convert to DATETIME instead. You just need to find the right format. (If your string value isn't already in a supported format, you may need to do some work...) That's what the value is, after all - why use BigInt at all?

Note that if you correct the schema to use an appropriate data type, it's likely to be much more efficient than having to convert it all over the place. For example, an index on the string column won't help much for that sort of query, whereas if you can change it to an indexed DATETIME value, the index can do most of the work.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top