Search code examples
sql-servervarchardifftime

Get Minute difference from two SQL columns


I have two columns in a table: 1st column only stores hhmm (Ex. 2350 aka 11:50pm) in varchar(257) format. 2nd column is the timestamp.

How do I get the minute difference between the two?

Here's the example of two columns. When in Management Studio, I click Alt + F1 to view info about the table, I am told Column 1 is varchar type and Column 2 is Datetime type:

enter image description here


Solution

  • This would have been a lot quicker and easier if you had provided this as consumable data. I did not bother typing all your sample data. The challenge here is that the data is improperly stored. I realize this is outside your control but you still have to force this back into a usable datatype. You will need to add some validation to this to ensure that the values are valid times. This also doesn't handle crossing day boundaries but given the nature of the data I don't know how you could even pretend to deal with that well.

    create table #Something
    (
        Col1 varchar(10)
        , Col2 datetime
    )
    
    insert #Something
    select '1230', '2014-12-19 13:09:00.000' union all
    select '1350', '2015-08-10 14:49:00.000'
    
    select Col1
        , Col2
        , DATEDIFF(minute, cast(STUFF(Col1, 3, 0, ':') as time), CAST(Col2 as time))
    from #Something