關于排序的存儲過程
各位大哥請幫忙:
寫一個存儲過程輸入七個數如( "12,56,45,87,123,44,50 ")執行存儲過程后要求從小到大排列( "12,44,45,50,56,87,123 ")謝謝,大哥們指教!
------解决方案--------------------create proc p (@s varchar(8000))
as
declare @re varchar(8000)
declare @tb table(col int)
set @s=@s+ ', '
set @re= ' '
while charindex( ', ',@s)> 0
begin
insert into @tb values(left(@s, charindex( ', ',@s)-1))
set @s=substring(@s,charindex( ', ',@s)+1,8000)
end
select @s=@s+ ', '+cast(col as varchar) from @tb order by col
select stuff(@s,1,1, ' ')
go
exec p '12,56,45,87,123,44,50 '
drop proc p
------解决方案----------------------Description:建立函数
CREATE function splitstr(@SourceSql varchar(8000),@StrSeprate varchar(5))
returns @temp table(F1 INT)
as
begin
declare @i int
set @SourceSql=rtrim(ltrim(@SourceSql))
set @i=charindex(@StrSeprate,@SourceSql)
while @i> =1
begin
insert @temp values(left(@SourceSql,@i-1))
set @SourceSql=substring(@SourceSql,@i+1,len(@SourceSql)-@i)
set @i=charindex(@StrSeprate,@SourceSql)
end
if @SourceSql <> ' ' insert @temp values(@SourceSql)
return
end
--一条语句查出结果
select * from dbo.splitstr( '12,44,45,50,56,87,123 ', ', ') order by F1 asc
------解决方案-------------------- /*
功能:实现split功能的函数
*/
create function fn_split
(
@inputstr varchar(8000),
@seprator varchar(10)
)
returns @temp table (a varchar(200))
as
begin
declare @i int
set @inputstr = rtrim(ltrim(@inputstr))
set @i = charindex(@seprator, @inputstr)
while @i > = 1
begin
insert @temp values(left(@inputstr, @i - 1))
set @inputstr = substring(@inputstr, @i + 1, len(@inputstr) - @i)
set @i = charindex(@seprator, @inputstr)
end
if @inputstr <> '\ '
insert @temp values(@inputstr)
return
end
go
--创建存储过程
create proc sp_test (@input varchar(1000),@output varchar(1000) output)
as
create table #t (a int)
insert into #t (a)
select a
from dbo.fn_split(@input, ', ')
declare @s varchar(1000)
set @s= ' '
select @s=@s + ', ' + cast(a as varchar(100)) from #t order by a
set @s=stuff(@s,1,1, ' ')
set @output = @s
go
declare @a varchar(100),@b varchar(1000)
set @a = '12,56,45,87,123,44,50 '
exec sp_test @a , @b output
select @b
drop function dbo.fn_split
drop proc sp_test
/*
返回:
12,44,45,50,56,87,123
*/
------解决方案-------------------- /*
功能:实现split功能的函数
*/
create function fn_split
(
@inputstr varchar(8000),
@seprator varchar(10)
)
returns @temp table (a varchar(200))
as
begin
declare @i int
set @inputstr = rtrim(ltrim(@inputstr))
set @i = charindex(@seprator, @inputstr)
while @i > = 1
begin
insert @temp values(left(@inputstr, @i - 1))