Sql server 将整数(';其他表中的多少年')添加到日期列(日期)

Sql server 将整数(';其他表中的多少年')添加到日期列(日期),sql-server,Sql Server,我必须将customer.purchase\u date添加到item.expire\u date\u years中,并在customer.expire\u date中获得此结果,例如2017-01-16+2=2019-01-16 试过了,没用 declare @year int set @year= (select expire_date_years from item) declare @purchDate date set @purchDate= (select purchas

我必须将customer.purchase\u date添加到item.expire\u date\u years中,并在customer.expire\u date中获得此结果,例如2017-01-16+2=2019-01-16

试过了,没用

declare @year int   
set @year=
(select expire_date_years
from item)
declare @purchDate date   
set @purchDate=
(select purchase_date
from customer)
update customer
set expire_date=dateadd(yyyy,cast(@year as date),@purchDate)
客户

create table customer
(id int primary key identity(1,1),
name nvarchar(50),
purchase_date date,
expire_date date
)
insert into customer values('John','20170116')
项目

create table item(
id int primary key identity(1,1),
name nvarchar(100),
expire_date_years int,
)

insert into item values('butter',2)

你很接近,只需更改你的DATEADD通话。需要关键字“year”并将金额作为整数,不要强制转换

update customer
set expire_date=DATEADD(YEAR, @year , @purchDate)
编辑: 好吧,你在评论中描述的错误与你如何给日期添加时间无关,因为你没有专注于一个项目。因此,它应该适用于您的示例,但不能直接扩展到更大的系统。让我们稍微扩展一下,使它看起来更像一个真实的系统-在要更新过期日期的表中放置对Item.ID的引用,然后使用该引用查找该项的单个过期年数。我转换为表变量,因为我今天无法让Fiddler工作,我不想在数据库日志中更改模式,但它看起来应该足够相似,您可以理解

DECLARE @customer table 
(id int primary key identity(1,1),
name nvarchar(50), purchase_date date, PurchasedItem INT, expire_date date )

insert into @customer values ('John','2017-01-16', 1, NULL)
    , ('Alice','2017-02-22', 1, NULL)
    , ('John','2017-01-11', 2, NULL), ('Alice','2017-02-23', 2, NULL)

DECLARE @item table (id int, name nvarchar(100),expire_date_years int)

insert into @item values(1, 'butter',2), (2, 'Soup',3)
--Look at the tables before update, this feeds the below "UPDATE"
SELECT * FROM @customer as C INNER JOIN @item as I on C.PurchasedItem = I.id 

UPDATE @customer SET expire_date = DATEADD(YEAR, I.expire_date_years, purchase_date ) 
FROM @customer as C INNER JOIN @item as I on C.PurchasedItem = I.id 
--Now look at the result
SELECT * FROM @customer as C 

用您正在使用的数据库标记您的问题。我在设置年份和设置purchDate时出错:(Msg 512,级别16,状态1,第13行)子查询返回的值超过1。当子查询后跟=,!=,=或子查询用作表达式时,不允许这样做。