如何在存储过程中实现冒泡排序

jojo731 2006-01-18 08:15:54
我创建一个表,其中有code和name字段,分别是int和char类型,想写一个存储过程用游标实现对code字段冒泡排序,请高手指教!在线等!
...全文
302 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
ReViSion 2006-01-18
  • 打赏
  • 举报
回复
老总就是老总
mislrb 2006-01-18
  • 打赏
  • 举报
回复
create table #t(id int identity(1,1),code int,name varchar(10))
insert #t
select 7,'aa1' union all
select 9,'aa2' union all
select 2,'aa3' union all
select 16,'aa4' union all
select 8,'aa5' union all
select 5,'aa6' union all
select 12,'aa7' union all
select 13,'aa8' union all
select 14,'aa9'

declare @n int,@id0 int,@code0 int,@name0 varchar(10),@id int,@code int,@name varchar(10)

select @id0=0,@n=max(id) from #t
while @n<>0
begin
declare c_t cursor for select [id],code,[name] from #t where id>=@id0-1
open c_t
fetch next from c_t into @id0,@code0,@name0

while @@fetch_status=0
begin
fetch next from c_t into @id,@code,@name
if @@fetch_status=0
begin
if @code0>@code
begin
update #t set code=@code,name=@name where id=@id0
update #t set code=@code0,name=@name0 where id=@id
set @n=@id0
goto nextcode
end
select @id0=case when @code0>@code then @id0 else @id end,@code0=@code,@name0=@name--,@n=@id
end
end
set @n=@n-1
nextcode:
close c_t
deallocate c_t
end
select * from #t


zheninchangjiang 2006-01-18
  • 打赏
  • 举报
回复

没法完成
jojo731 2006-01-18
  • 打赏
  • 举报
回复
老总发话的,没办法,我还是新手,不会用游标在存储过程里实现冒泡排序
caral525 2006-01-18
  • 打赏
  • 举报
回复
为什么非要在过程里做冒泡排序,SQL语法不是有排序么?

22,206

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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