我想实现一个功能,将数据库记录中,满足字段1的值不同,但字段2的值相同时的N条记录,且此N记录中的满足CreateTime(创建记录的时间)靠后的N-1条记录的字段2的值都改成一个随机数。不知道大家有没有明白?举个例子吧!
我现在有一个表Table1,结构和数据如下。
ID Field1 Field2 CreateTime
1 0001 a 2007-01-01
2 0001 e 2007-01-01
3 0002 a 2007-01-11
4 0002 b 2007-01-11
5 0002 c 2007-01-11
6 0003 a 2007-01-12
7 0003 b 2007-01-12
8 0003 c 2007-01-12现我想得出的结果是:将ID为3,6,7,8 的Field2的值都改成一个随机数字符串。
谢谢高手指教!

解决方案 »

  1.   

    update Table1  set Field2 = rand(id) where exists(select 1 from table1 a where a.Field2 = Table1.Field2 and a.ID<Table1.ID)
      

  2.   

    declare @t table (
    ID int,
    Field1 varchar(10),
    Field2 varchar(10),
    CreateTime datetime
    )insert @t select
    1, '0001', 'a', '2007-01-01'
    union all select
    2, '0001', 'e', '2007-01-01'
    union all select
    3, '0002', 'a', '2007-01-11'
    union all select
    4, '0002', 'b', '2007-01-11'
    union all select
    5, '0002', 'c', '2007-01-11'
    union all select
    6, '0003', 'a', '2007-01-12'
    union all select
    7, '0003', 'b', '2007-01-12'
    union all select
    8, '0003', 'c', '2007-01-12'update t
    set field2=char(ascii('A')+cast(25*rand(id*10000) as int))
    from @t t
    where exists (
    select 1 from @t
    where field2=t.field2
    and CreateTime<t.CreateTime
    )
    select * from @t--结果
    ID          Field1     Field2     CreateTime                                             
    ----------- ---------- ---------- ------------------------------------------------------ 
    1           0001       a          2007-01-01 00:00:00.000
    2           0001       e          2007-01-01 00:00:00.000
    3           0002       G          2007-01-11 00:00:00.000
    4           0002       b          2007-01-11 00:00:00.000
    5           0002       c          2007-01-11 00:00:00.000
    6           0003       U          2007-01-12 00:00:00.000
    7           0003       A          2007-01-12 00:00:00.000
    8           0003       F          2007-01-12 00:00:00.000(所影响的行数为 8 行)
      

  3.   

    Haiwer(海阔天空)的再增加一个过滤条件把Field1!=t.Field1