2016-10-14 98 views
-1

我有一個表中的兩個字段,一個varchar字段是保存值,如3,4,11或NULL轉換爲3,4或11年。SQL查詢更新日期時間字段基於當前日期+值

最近,我在類型日期的相同表格中引入了新列,我在這裏保存日期,並最終替換之前的字段。

這些是實際的列:

enter image description here

所以對於新LeaseRemainingFirstBreakDate場我想要做的GETDATE()+中如果它不是空的LeaseRemainingFirstBreak字段中的值。

由於提前,Laziale

+0

你使用[DATEADD](http://www.w3schools.com/sql/func_dateadd.asp)嗎? – techspider

+0

像這樣的事情DATEADD(yyyy,LeaseRemainingFirstBreak,GETDATE())我假設? – Laziale

+0

是的,你需要處理NULL爲第二個參數 – techspider

回答

0

UPDATE [tablename] SET [LeaseRemainingFirstBreakDate] = dateadd(year, [LeaseRemainingFirstBreak], convert(date, getDate()) where [LeaseRemainingFirstBreakDate] is not null

轉換保證了在格式化該字段中的其它值中示出的日期格式相匹配。

+0

爲什麼你需要'CONVERT'作爲'GETDATE()'? – techspider

+0

否則它會返回小時/分鐘/秒 - 只是與示例中顯示的現有日期的命名約定相匹配。 – finjo

+0

獲取此錯誤參數數據類型nvarchar對於dateadd函數的參數2無效。 – Laziale

0

隨着問題的不確定性,

如果喲想忽略空值和更新其他行,

UPDATE YourTable 
SET LeaseRemainingFirstBreakDate = DATEADD(yyyy, CONVERT(INT, LeaseRemainingFirstBreak), GETDATE()) 
WHERE LeaseRemainingFirstBreak IS NOT NULL 

如果你要考慮那些具有NULL值的當前日期,

UPDATE YourTable 
SET LeaseRemainingFirstBreakDate = DATEADD(yyyy, CONVERT(INT, COALESCE(LeaseRemainingFirstBreak,0)), GETDATE()) 
0

Via使用DATEADD功能。

Eample:

Create table Test (LeaseRemainingFirstBreakDate int ,LeaseRemainingFirstBreak datetime) 
Go 

Insert into Test (LeaseRemainingFirstBreakDate ,LeaseRemainingFirstBreak ) 
Values (2, null), 
     (12, null), 
     (22, null), 
     (Null, null), 
     (Null, null) 
GO 

Select * from Test 

結果:

enter image description here

Update Test 
Set LeaseRemainingFirstBreak = DATEADD(YEAR,LeaseRemainingFirstBreakDate,getDate()) 
where LeaseRemainingFirstBreakDate is Not NULL 

結果

enter image description here

注:我通過使用

ISNULLCOLLASE功能排除有NULL,同時通過使用

where LeaseRemainingFirstBreakDate is Not NULL 

更新行,如果你想更新其他空行,亨德爾空。

相關問題