修改前n条记录的问题

lxwyk 2005-07-31 01:25:28
我想修改一个表中前n条,比如前10条记录的某个字段的值,请问该如何做。
...全文
135 13 打赏 收藏 转发到动态 举报
写回复
用AI写文章
13 条回复
切换为时间正序
请发表友善的回复…
发表回复
lxwyk 2005-08-03
  • 打赏
  • 举报
回复
自己顶一下
helodd 2005-08-03
  • 打赏
  • 举报
回复
使用游标~~~~~~~
测试ms-sql server

create 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'

go

select * from abc
go

declare @ID int
declare @icount int
declare mm_Cursor scroll cursor for select [id] from abc

set @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
Teng_s2000 2005-08-02
  • 打赏
  • 举报
回复
好啊,学习的好几会
lxwyk 2005-08-02
  • 打赏
  • 举报
回复
to 凋花溅泪:呵呵,我可没有抬杠的意思,我们在排序的时候一定是按照关键字么?我只是想找一个通用一点的方法,其实,解一对于大多数情况都是可以的,但比如我写了一个视图,其中的排序字段是一个可以重复的字段,我要实现上述操作,可以么?

哈哈,突然想到一点,问题可以解决了,解一的方法修改一下就可以了:
update 表名 set 字段=100 where 字段 in(select top 10 字段 from 表名 )
其中:
1)字段为关键字段,可以是组合关键字,如果是组合关键字,则将各组合关键字转为字符类型连接起来作为一个字段,另外,在“select top 10 字段”中的字段也是同样是组合关键字转为字符串类型的连接。
2)不需亚有order by语句,不打乱已有的排序。
这钟方法相当于先取出前10条,然后再依次比较表中的每一条,如果和此10条相同,则满足条件,不过,因为没有打乱原来表的顺序,所以,只会比较表中的前10条数据。

先不结帖,还有别的方法么?一起讨论一下。
hqhhh 2005-08-02
  • 打赏
  • 举报
回复
楼上说的是:
你没有一个关键字段吗?不可能吧
yu98041154 2005-08-02
  • 打赏
  • 举报
回复
回楼上,解一中用来连接两条语句的字段应该是用主键啊,依你的看法这个字段所有取值都一样好像是在故意找麻烦,抬杠啊
lxwyk 2005-08-01
  • 打赏
  • 举报
回复
解一存在这样的问题,如果我的这个字段所有取值都一样呢,比如,都取0,就起不到作用了。

解二在进行频繁的操作时有些问题,性能不高,我希望能够在sqlserver上写,可以将解二的方法改装一下,使用游标来完成,但是很费时间因为,select top n得到的游标是只读的。

icerainy 2005-07-31
  • 打赏
  • 举报
回复
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;
Teng_s2000 2005-07-31
  • 打赏
  • 举报
回复
楼主,虽然昨天找工作不顺利,面试得人说现在delphi开发没人要了,但是我还是忍不住要来到delphi社区看看,帮你解决一下问题!我在sql server数据库中试验成功了
update 表名 set 字段=100 where 字段 in(select top 10 字段 from 表名 order by 字段)
cdsgajxlp 2005-07-31
  • 打赏
  • 举报
回复
update 表名 set 字段=100 where 字段 in(select top 10 字段 from 表名 order by 字段)
jkx01whg 2005-07-31
  • 打赏
  • 举报
回复
正解
hqhhh 2005-07-31
  • 打赏
  • 举报
回复
一楼二楼正解
sluger 2005-07-31
  • 打赏
  • 举报
回复
两个都行

2,497

社区成员

发帖
与我相关
我的任务
社区描述
Delphi 数据库相关
社区管理员
  • 数据库相关社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧