SQL版冒泡排序 双层while循环

SQL没有for循环,没有数组概念。

SQL可以用关键字order by排序。

declare

  @str varchar(500),

  @Count int,

  @i int,

  @j int,

  @num1 int,

  @num2 int,

  @temp int

  

  --接收一串字符

  SET @str='98 108 102 91 89 88 98 91 97 102'

  --按空格拆开插入表中,把' '替换成' union all select '

  SELECT @str=REPLACE(@str,' ',' union all select ')



  --创建临时表

  CREATE TABLE table1 (ID INT IDENTITY(1,1),num int)

  --处理SQL语句

  SELECT @str='insert into table1 (num) select '+@str

  --执行SQL语句

  EXEC(@str)

  

  IF exists(select * from table1)

  begin

    --一共有多少个数(用来计算需要循环多少次)

    select @Count=Count(num) from table1

    

    --开始循环

    set @i=1

    

    --外循环

    --只知道一个数一共要比较几次(比如有4个数,第一个要比较3次,第二个要比较2次,第三个比较1次)

    --知道了比较次数,然后才具体做排序(内循环)

    while (@i<@Count)

    begin

      --内循环while结束后,开始第二次外循环,重新开始,重新赋初值(像for(int @j=@i...))

      set @j=@i

      --内循环

      --具体比较的过程(比如要比较3次,第一次和第2个数比较,第二次和第3个数比较,第三次和第4个数比较)

      while (@j<@Count)

      begin

          --要比较的第一个数(第一个数不变)

          select @num1=num from table1 where ID=@i

          --要比较的第二个数(第二个数按次数增加)

          select @num2=num from table1 where ID=@j+1

          if @num1>@num2

          begin

              --交换数字

              --把大的数先放一边

              set @temp=@num1

              --把小的数放到前边

              update table1

              set num=@num2

              where ID=@i

              --把大的放后边

              update table1

              set num=@temp

              where ID=@j+1

          end

          set @j=@j+1

      end

      set @i=@i+1

   end

end

  

  select * from table1

  drop table table1

  

  GO

  -----------------------------------------------------------

 

SQL版冒泡排序 <wbr>双层while循环


SQL版冒泡排序 <wbr>双层while循环

SQL版冒泡排序 <wbr>双层while循环

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值