0

Am newbie to SQL Server. In that i need to sort the following data

1, 1AB, 1AA, 20, 3C, 4D 

into

1, 1AA, 1AB, 3C, 4D, 20.

My coding is of

IF EXISTS ( SELECT name FROM sysobjects WHERE name = 'getIntPortion')
 DROP FUNCTION getIntPortion
GO    
CREATE FUNCTION dbo.getIntPortion ( @inputVarchar varchar(255))
RETURNS VARCHAR(255)
AS
BEGIN
 WHILE(PATINDEX('%[^0-9]%', @inputVarchar) ) > 0
 BEGIN
 --then remove that one character, then continue
 SET @inputVarchar = REPLACE(@inputVarchar
 , SUBSTRING(@inputVarchar, PATINDEX('%[^0-9]%', @inputVarchar), 1)
 , '')
 END
 RETURN @inputVarchar
END

SELECT km_ph_act_chapt_no FROM [KM_DB].[dbo].[km_ph_act_chapters]
ORDER BY CONVERT(INT, dbo.getIntPortion(km_ph_act_chapt_no))

For this Alpha is not ordering... Hopefully waiting for reply.

Thanks and Regards,

Asker

5
  • Its sorting with NUmeric... But Not in the above order i have mentioned. Commented Aug 13, 2012 at 13:05
  • Can you explain the algorithm you're trying to sort by? Are you trying to sort by the numeric portion as a number, and then by alpha within a number? Commented Aug 13, 2012 at 13:07
  • 1
    Hi Steven, I have to sort with Alpha within a Number Commented Aug 13, 2012 at 13:09
  • 1
    If the rows had two columns, one for the int part, one for the varchar part, it would be easy Commented Aug 13, 2012 at 13:14
  • Jodrell: Actually i need to sort only by the chapter Number. So consider like.. Chapter 1, Chapter 1B, Chapter 2 etc..., Commented Aug 13, 2012 at 13:20

3 Answers 3

3

Try:

ORDER BY CONVERT(INT, dbo.getIntPortion(km_ph_act_chapt_no)), km_ph_act_chapt_no;

But I would recommend against using a scalar function like this.

Sign up to request clarification or add additional context in comments.

Comments

2

Assuming your function works correctly, change the order by to

SELECT km_ph_act_chapt_no FROM [KM_DB].[dbo].[km_ph_act_chapters] 
ORDER BY CONVERT(INT, dbo.getIntPortion(km_ph_act_chapt_no)) ,
   km_ph_act_chapt_no

Comments

1

add a secondary sort so that it will sort the letters after you have sorted by the leading number

e.g

SELECT km_ph_act_chapt_no FROM [KM_DB].[dbo].[km_ph_act_chapters]
ORDER BY CONVERT(INT, dbo.getIntPortion(km_ph_act_chapt_no)), km_ph_act_chapt_no

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.