2011-06-23 59 views
5

我在db中有一個列偏移量爲varchar(50),其中包含一個值,如05:30:00-2:15:00在SQL服務器中從日期時間加上或減去時間

我需要從DATETIME數據類型2011-07-22 14:51:00的另一列中增加或減去此值。

+12

在那裏你從來沒有接受答案的理由? –

+2

這是一個非常有用的問題,保羅麥克萊恩的答案是現貨。標記爲已接受。 – gligoran

回答

16

嘗試像 -

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

完美答案!,這正是我所尋找的...... :) – Bravo

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 

注意,這考慮到了負調整時期了。

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() 
)