欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

用sql server存储过程写一个排序的代码

程序员文章站 2022-03-11 16:47:43
declare @a int,@str nvarchar(100),@i int,@j int,@m int, @n int,@q intcreate table table_order( id int, num int, ) set @str='1,3,2,5,4,6';set @a=len(@str)set @i=1 while @i<=(@a+1)/2 begin...
declare @a int,@str nvarchar(100),@i int,@j int,@m int, @n int,@q int
create table table_order(     
         id int,
         num int,
         ) 
set @str='1,3,2,5,4,6';
set @a=len(@str)
set @i=1
        while @i<=(@a+1)/2         
        begin 
                 insert table_order(id,num) values(@i,substring(@str,2*@i-1,1))  --将str里的数直接插入表中 
                  set @i=@i+1
        end 

        select * from table_order   --查询表的初始数据
set @i=1
set @j=1
while @i<=(@a+1)/2
        begin
                 set @m= (select num from table_order where id =@i)
                 set @j=@i+1
                        while @j<=(@a+1)/2 
                        begin 
                        set @n= (select num from table_order where id =@j )
                        if @m>=@n
                        begin
                        update table_order set num=@m where id=@j
                        update table_order set num=@n where id=@i   
                        end
                        set @j=@j+1
                        end
                set @i=@i+1
end        
select * from table_order

运行结果:
用sql server存储过程写一个排序的代码

本文地址:https://blog.csdn.net/qq_44108455/article/details/107637085

相关标签: 基础学习