# 求字符串排序？'051703121129'

billrobin 2010-09-23 08:40:46

``'051703121129'``

'05 17 03 12 11 29'-------'03 05 11 12 17 29'

...全文
69 点赞 收藏 5

5 条回复

cheniwantyou 2010-09-24
[Quote=引用 3 楼 sqlcenter 的回复:]
SQL code
create function fn_test(@s varchar(1000))
returns varchar(1000)
as
begin
declare @t table (s varchar(2))
declare @i int, @ret varchar(1000)
select @i = 0, @ret = ''
wh……
[/Quote]

OK,以上乃正解。

``````--瞎弄的
IF OBJECT_ID('f_test') IS NOT NULL
DROP FUNCTION f_test
GO

CREATE FUNCTION f_test (@var VARCHAR(50))
RETURNS VARCHAR(50)
AS
BEGIN
DECLARE @test TABLE (tt VARCHAR(2))

WHILE LEN(@var) > 0
BEGIN
INSERT  INTO @test
SELECT  LEFT(@var,2)
SELECT  @var = STUFF(@var,1,2,'')
END

DECLARE @str VARCHAR(50)
SELECT  @str = ISNULL(@str,'') + t.tt
FROM    (SELECT TOP 100
tt
FROM   @test
ORDER BY CAST(tt AS INT)
) AS t
RETURN @str
END
GO

DECLARE @var VARCHAR(50)
SET @var = '051703121129'
SELECT dbo.f_test(@var)``````

SQLCenter 2010-09-23
``````create function fn_test(@s varchar(1000))
returns varchar(1000)
as
begin
declare @t table (s varchar(2))
declare @i int, @ret varchar(1000)
select @i = 0, @ret = ''
while @i < (len(@s)+1)/2
begin
insert @t select substring(@s,@i*2+1,2)
set @i = @i + 1
end
select @ret = @ret + s from @t order by s
return @ret
end
go

select dbo.fn_test('051703121129') --> 030511121729
``````

``````if object_id('f_GetStr') is not null
drop function f_GetStr
go
create function dbo.f_GetStr(@s varchar(100))
returns varchar(100)
as
begin
declare @t table(s varchar(10))
while len(@s)>0
begin
insert @t select left(@s,2)
set @s=stuff(@s,1,2,'')
end
select @s=''
select @s=@s+s
from @t
order by s
return @s
end
go

declare @s char(20)
set @s='051703121129'
select result=dbo.f_GetStr(@s)

/*
result
-------------
030511121729
*/``````

2.1w+

MS-SQL Server 疑难问题

2010-09-23 08:40