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