以上写错,修改如下比如
表A
Date Value
20050205 (null)
20050215 (null)
表B
Date Value
20050201 100
20050210 200从表B中取数更新到表A的Value,规则是取离表A中日期向后最近的Value.
以上例子更新后的结果应该是:
表A更新后
Date Value
20050205 100      (表B中20050201记录日期向后最近)
20050215 200 (表B中20050210记录日期向后最近)求SQL语句.要求不用到函数和游标.

解决方案 »

  1.   

    update a set value=b.value from ta a,tb b 
    where a.[date]>b.[date] not exists(select 1 from tb where [date]<a.[date] and [date]>b.[date] )
      

  2.   

    create table A
    (
       date varchar(10),
       value int
    )create table B
    (
       date varchar(10),
       value int
    )insert A select '20050205', null
    insert A select '20050215', null
    insert B select '20050201', 100
    insert B select '20050210', 200
    update A set value=(select top 1 value from B  where date<=A.date order by date DESC)
      

  3.   

    感谢两位的作答.
     scmail81(琳·风の狼) 的答案非常正确.
     wgsasd311(自强不息)  的答案在一般情况下也能得到正确的结果,但not exists(select 1 from tb where [date]<a.[date] and [date]>b.[date] )并不能完全取得"日期向后最近"的效果,只能取得物理位置向后最近的记录.
    比如在以下语句:
    create table A
    (
       date varchar(10),
       value int
    )create table B
    (
       date varchar(10),
       value int
    )insert A select '20050205', null
    insert A select '20050215', null
    insert B select '20050202', 200   --注意这里把20050202写在20050201之前
    insert B select '20050201', 100   --并且两个日期都是小于A表所有日期
    update a set value=b.value from a, b 
    where a.[date]>b.[date] and  not exists(select 1 from b where [date]<a.[date] and [date]>b.[date] )
    select * from Adrop table A
    drop table B得到的结果是
    Date Value
    20050205 100
    20050215 100 而正确的结果应该是Date Value
    20050205 200
    20050215 200
      

  4.   

    楼主你测试错了,我的语句没能错误,你测试不对,我取的是别名(A,B)如果你的两个表正好是A ,B ,那别名要相应该下,否则后面的 not exists(select 1 from b where [date]<a.[date] and [date]>b.[date] )语句中[date]>b.[date]根本就是不成立的,因为系统区分不出后面的
    b.[date]和前面的[data]是两个表,原意是取前面表.楼主测试请稍改就可以测出效果了......
    create table A
    (
       date varchar(10),
       value int
    )create table B
    (
       date varchar(10),
       value int
    )insert A select '20050205', null
    insert A select '20050215', null
    insert B select '20050202', 200   --注意这里把20050202写在20050201之前
    insert B select '20050201', 100   --并且两个日期都是小于A表所有日期
    update a set value=t2.value from a , b t2
    where t2.[date]<a.[date] and  not exists(select 1 from b where [date]<a.[date] and [date]>t2.[date] )
    select * from Adrop table A
    drop table B
      

  5.   

    经测试,wgsasd311(自强不息) 的答案是正确的.
    是我在别名上的处理不当引起了以上发贴中的错误.
    感谢wgsasd311(自强不息)!
    遗憾的是贴子已结,无法调分.希望下次能再次得到你的帮助.