在SQL Server中添加或减去日期时间的时间

时间:2011-06-23 03:58:40

标签: sql sql-server stored-procedures

我在db中的列偏移量为varchar(50),其中包含05:30:00-2:15:00等值。

我需要在DATETIME数据类型为2011-07-22 14:51:00的其他列中添加或减去此值。

3 个答案:

答案 0 :(得分:16)

尝试类似的事情 -

select convert(datetime, '05:30:00') + GETDATE()

答案 1 :(得分:1)

您的数据库平台是什么?

在MS SQL上你会这样做......

-- Create some test data
create table dbo.MyData (
    Adjustment varchar(50) NOT NULL,
    BaseDate datetime NOT NULL
) on [primary]
go

insert into dbo.MyData ( Adjustment, BaseDate ) values ( '05:30:00', cast('2011-07-22 14:51:00' as datetime) )
insert into dbo.MyData ( Adjustment, BaseDate ) values ( '-2:15:00', cast('2011-06-12 10:27:30' as datetime) )
go

-- Perform the adjustment
select 
    c.Adjustment,
    c.BaseDate,
    c.AdjSecs,
    dateadd(s, c.AdjSecs, c.BaseDate ) as AdjustedDate
from (
    select 
        case 
        when left( Adjustment, 1 ) = '-' then -1 * datediff(s, 0, right( Adjustment, len(Adjustment) - 1 ))
        else datediff(s, 0, right( Adjustment, len(Adjustment) - 1 ))
        end as AdjSecs,
        Adjustment,
        BaseDate
    from dbo.MyData
) as c

注意,这也考虑了负调整期。

答案 2 :(得分:1)

将getdate()函数替换为日期列

DECLARE @mytime AS VARCHAR(10)

SET @mytime = '2:15:00'

SELECT DATEADD(
s
,CASE 
     WHEN SUBSTRING(@mytime,1,1)='-' 
           THEN -DATEDIFF(s,0, SUBSTRING(@mytime,2,LEN(@mytime)-1) 
           ELSE DATEDIFF(s,0, @mytime) 
     END
,GETDATE()
)