我想修改一个表中前n条,比如前10条记录的某个字段的值,请问该如何做。

解决方案 »

  1.   

    楼主,虽然昨天找工作不顺利,面试得人说现在delphi开发没人要了,但是我还是忍不住要来到delphi社区看看,帮你解决一下问题!我在sql server数据库中试验成功了
    update 表名 set 字段=100 where 字段 in(select top 10 字段 from 表名 order by 字段)
      

  2.   

    top n 好像在桌面数据库不能用,如果能用的话,用楼上的够简单
    不能用的话楼主可以定义一个变量控制 
    类似这样:
    var
      i:integer;
    begin
      i:=1;
      if table1.Active = false then
          table1.Open;
     with table1 do
     begin
      First;
           while not Eof do
           begin
            if i>10 then
              Last
            else
              begin
                Edit;
                FieldByName('字段名').AsString := 'newvalue';
                Post;
                i:=i+1;
                Next;
              end;
           end;
       end;
    end;
      

  3.   

    update 表名 set 字段=100 where 字段 in(select top 10 字段 from 表名 order by 字段)
      

  4.   

    解一存在这样的问题,如果我的这个字段所有取值都一样呢,比如,都取0,就起不到作用了。解二在进行频繁的操作时有些问题,性能不高,我希望能够在sqlserver上写,可以将解二的方法改装一下,使用游标来完成,但是很费时间因为,select top n得到的游标是只读的。
      

  5.   

    to 凋花溅泪:呵呵,我可没有抬杠的意思,我们在排序的时候一定是按照关键字么?我只是想找一个通用一点的方法,其实,解一对于大多数情况都是可以的,但比如我写了一个视图,其中的排序字段是一个可以重复的字段,我要实现上述操作,可以么?哈哈,突然想到一点,问题可以解决了,解一的方法修改一下就可以了:
    update 表名 set 字段=100 where 字段 in(select top 10 字段 from 表名 )
    其中:
     1)字段为关键字段,可以是组合关键字,如果是组合关键字,则将各组合关键字转为字符类型连接起来作为一个字段,另外,在“select top 10 字段”中的字段也是同样是组合关键字转为字符串类型的连接。
     2)不需亚有order by语句,不打乱已有的排序。
    这钟方法相当于先取出前10条,然后再依次比较表中的每一条,如果和此10条相同,则满足条件,不过,因为没有打乱原来表的顺序,所以,只会比较表中的前10条数据。  先不结帖,还有别的方法么?一起讨论一下。
      

  6.   

    使用游标~~~~~~~
    测试ms-sql servercreate table abc (id int,title varchar(100))go
    insert into abc
    select 1,'11111'
    union select 2,'11111'
    union select 3,'11111'
    union select 4,'11111'
    union select 5,'11111'
    union select 6,'11111'
    union select 7,'11111'
    union select 8,'11111'
    union select 9,'11111'
    union select 10,'11111'
    union select 11,'11111'
    union select 12,'11111'
    union select 13,'11111'
    union select 14,'11111'
    union select 15,'11111'
    union select 16,'11111'
    union select 17,'11111'
    union select 18,'11111'
    union select 19,'11111'
    union select 20,'11111'goselect * from abc
    godeclare @ID int
    declare @icount  int
    declare mm_Cursor scroll cursor for select [id] from abcset @Icount = 0
    open mm_Cursor
    fetch next from mm_Cursor into @ID
    while (@@fetch_status = 0) and (@icount<10)
    begin
     update abc set title='2222222' where [id]=@ID fetch next from mm_Cursor into @ID
     set @Icount = @iCount+1
    end
    close mm_cursor
    deallocate mm_cursor  
    select * from abc