CREATE FUNCTION dbo.Alphaorder (@str VARCHAR(50))
returns VARCHAR(50)
BEGIN
DECLARE @len INT,
@cnt INT =1,
@str1 VARCHAR(50)='',
@output VARCHAR(50)=''
SELECT @len = Len(@str)
WHILE @cnt <= @len
BEGIN
SELECT @str1 += Substring(@str, @cnt, 1) + ','
SET @cnt+=1
END
SELECT @str1 = LEFT(@str1, Len(@str1) - 1)
SELECT @output += Sp_data
FROM (SELECT Split.a.value('.', 'VARCHAR(100)') Sp_data
FROM (SELECT Cast ('<M>' + Replace(@str1, ',', '</M><M>') +
'</M>' AS XML) AS Data) AS A
CROSS APPLY Data.nodes ('/M') AS Split(a)) A
ORDER BY Sp_data
RETURN @output
END
SELECT dbo.Alphaorder ('juan') --> ajnu
-
1Have you tried anything towards what you are doing. A quick google search got me to stackoverflow.com/questions/41781/… sqlines.com/onlineankyskywalker– ankyskywalker2019-11-27 06:03:25 +00:00Commented Nov 27, 2019 at 6:03
1 Answer
That looks like a badly written function to begin with.
If you need to do something like that function does in Oracle SQL, you can do it directly with Oracle SQL features, you don't need to write your own function.
Even if for some reason you do need to write a function, it is perhaps easiest to let SQL do the work for you (the same as you would do if your context was straight SQL).
Something like this:
create or replace function alphaorder(str varchar2) return varchar2
as
output varchar2(4000);
begin
select listagg(ch) within group (order by ch)
into output
from ( select substr(str, level, 1) as ch
from dual
connect by level <= length(str)
)
;
return output;
end;
/
Note that in Oracle you can't limit the length of the input or of the output string; you can only declare the data type. Then in the function itself you can check length and throw an error if the input is longer than 50 characters, but why bother? Let the function work in full generality.
Here's how you would call the function (and check that it works as required):
select alphaorder('juan') as alpha_ordered from dual;
ALPHA_ORDERED
-------------
ajnu