有二个表:表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    |
--------------------------

解决方案 »

  1.   

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

  2.   

    --> 测试数据:[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,nullselect * 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*/
      

  3.   

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

  4.   


    select 
        b.starttime, [endtime] = dateadd(day, a.duration, b.starttime)
    from
        table2 a
        left join table1 b
    on a.id = b.id
      

  5.   

    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,nullupdate table2
    set endtime = dateadd(dd,duration,n.starttime)
    from table2 m , table1 n where m.id = n.idselect * from table2drop 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 行)
    */
      

  6.   

    update
     table2
    set
     endtime=dateadd(dd,duration,starttime)
    from 
     table1 join table2
    on
     table1.id=table2.id