如何使一个表中的时间加上一个整数天数形成一个新时间?

seaxiao 2010-04-12 10:21:27
有二个表:表1是id号和开始时间,表2是id号和持续天数,我想把表1中的开始时间加上表2中的持续时间(天为单位),写入到表2结束时间内?或查询出开始时间+持续时间也行.sql语句应该怎么写?
table1(id,starttime)
----------------
id | starttime
1 | 2010-4-1
2 | 2010-5-10
----------------
table2(id,duration,endtime)
-----------------------------
id|duration|endtime
1| 2 |
1| 5 |
2| 7 |
--------------------------
...全文
106 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
--小F-- 2010-04-12
  • 打赏
  • 举报
回复
update
table2
set
endtime=dateadd(dd,duration,starttime)
from
table1 join table2
on
table1.id=table2.id
seaxiao 2010-04-12
  • 打赏
  • 举报
回复
非常感谢各位,学习了。
dawugui 2010-04-12
  • 打赏
  • 举报
回复
create table [table1]([id] int,[starttime] datetime)
insert [table1]
select 1,'2010-4-1' union all
select 2,'2010-5-10'
create table [table2]([id] int,[duration] int,[endtime] datetime)
insert [table2]
select 1,2,null union all
select 1,5,null union all
select 2,7,null

update table2
set endtime = dateadd(dd,duration,n.starttime)
from table2 m , table1 n where m.id = n.id

select * from table2

drop table table1, table2

/*
id duration endtime
----------- ----------- ------------------------------------------------------
1 2 2010-04-03 00:00:00.000
1 5 2010-04-06 00:00:00.000
2 7 2010-05-17 00:00:00.000

(所影响的行数为 3 行)


*/
老黎 2010-04-12
  • 打赏
  • 举报
回复

select
b.starttime, [endtime] = dateadd(day, a.duration, b.starttime)
from
table2 a
left join table1 b
on a.id = b.id
dawugui 2010-04-12
  • 打赏
  • 举报
回复
update table2
set endtime = dateadd(dd,duration,n.starttime)
from table2 m , table1 n where m.id = n.id
Mr_Nice 2010-04-12
  • 打赏
  • 举报
回复
--> 测试数据:[table1]
if object_id('[table1]') is not null drop table [table1]
create table [table1]([id] int,[starttime] datetime)
insert [table1]
select 1,'2010-4-1' union all
select 2,'2010-5-10'
--> 测试数据:[table2]
if object_id('[table2]') is not null drop table [table2]
create table [table2]([id] int,[duration] int,[endtime] sql_variant)
insert [table2]
select 1,2,null union all
select 1,5,null union all
select 2,7,null

select * from [table1]
select * from [table2]


SELECT B.id,A.starttime,B.duration,[comp]=DATEadd(d,B.duration,A.starttime)
FROM dbo.table1 A
INNER JOIN dbo.table2 B ON B.id = A.ID

/*
id starttime duration comp
1 2010-04-01 00:00:00.000 2 2010-04-03 00:00:00.000
1 2010-04-01 00:00:00.000 5 2010-04-06 00:00:00.000
2 2010-05-10 00:00:00.000 7 2010-05-17 00:00:00.000*/
playwarcraft 2010-04-12
  • 打赏
  • 举报
回复
update table2
set endtime=dateadd(day,duration,starttime)
from table1,table2
where table1.id=table2.id
playwarcraft 2010-04-12
  • 打赏
  • 举报
回复
dateadd(day,1,getdate())

34,588

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧