2016-10-14 97 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 

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

相关问题