Search code examples
sqlsql-serverdatetimesqldatetime

How to form a string with parts of dates in SQL Server


I have datetimes in a table, in this manner (two in each row in a table):

Row 1: 2012-06-31 01:00:00
Row 2: 2012-06-31 02:00:00
Row 3: 2012-06-31 03:00:00
Row 4: 2012-06-31 04:00:00
...

And I want to get each hour as an interval, to get it from a report:

For the first row:  From 1 to 2
For the second row: From 2 to 3
...
For each row: 'From [hour(date)] to [hour(date)+1]'

But I don't stop getting "conversion error" with every combination con CONVERT, CAST, DATEPART or DATEADD.

I am new in dealing this kind of issues with SQL... How would you do this?


Solution

  • Try this:

    Use DatEPART Function with CAST

    declare @dte datetime='2012-01-01 05:02:00'
    select  'From '+ cast (DATEPART(HH,@dte) as char(2))+
                 'to ' +cast(  DATEPART(HH,@dte)+1 as char(2))
     
    

    SQL Fiddle Demo

    EDIT:

    IF you want to retrieve from a table

    declare @t table(dte datetime);
    insert into @t values('2012-01-01 05:02:00');
    insert into @t values('2012-01-01 06:02:00');
     
    select  'From '+ cast (DATEPART(HH,dte) as char(2))+
                 'to ' +cast(  DATEPART(HH,dte)+1 as char(2))
                 from @t