sql查询根据currentdate +值更新datetime字段

时间:2016-10-14 15:51:09

标签: sql sql-server tsql

我在表中有两个字段,一个varchar字段可以保存3,4,11或NULL等值,转换为3年,4年或11年。

最近我在类型为date的同一个表中引入了新列,我将保存日期,最终将取代之前的字段。

这些是实际的列:

enter image description here

因此,对于新的LeaseRemainingFirstBreakDate字段,我想在LeaseRemainingFirstBreak字段中执行GETDATE()+值,如果它不为空。

3 个答案:

答案 0 :(得分:0)

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

转换确保格式与该字段中其他值中显示的日期格式匹配。

答案 1 :(得分:0)

问题含糊不清,

如果你想忽略NULL并更新其他行,

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

答案 2 :(得分:0)

通过使用 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

注意:我在使用

更新时排除了具有NULL的行
  where LeaseRemainingFirstBreakDate is Not NULL

如果您想更新其他空行,请使用

更新handel Null

ISNULLCOLLASE个函数。