在一张表中,如果有A,B,C,D共4个字段,如何用select语句查询出A字段为某个值(譬如为1)的记录,并且如果存在D字段值等于A字段值的记录,则用这条记录的C字段值取代先前查询出的值为1的记录中的C字段的值,如果不存在就保持原C字段的值不变

解决方案 »

  1.   

    update _b set c=_a.c
    from t1 _a join t1 _b
    on _a.a=_b.d
    where _a.a=1
      

  2.   

    update table t1 set t1.C=t2.C
    where exists(select * from table t2 where t2.D=t2.A where t2.A=1)
    and t1.A=1
      

  3.   

    CREATE TABLE [dbo].[txt](
    A [int]  NOT NULL,
    B [int]  NOT NULL,
    C [int]  NOT NULL,
    D [int]  NOT NULL)
    insert into [txt] 
    select 1,2,3,4 union all
    select 4,3,2,1 
    UPDATE [dbo].[txt] SET [txt].C=(SELECT A.C FROM [dbo].[txt] A INNER JOIN [dbo].[txt] B  ON B.A=1 AND A.D=B.A)
    WHERE [txt].A=1
    select * from [dbo].[txt] where A=1
    DROP TABLE  [dbo].[txt]