I have seen very often people ask for sorting alphabetically and moreover if it has a number as a part of string that also should be sorted .
Take a look at this example. I used PATINDEX function to find a position at which 'numeric' part begins along with SUBSTRING started from first postion thrue the whole string.RIGHT function just adds '00000' to string , so if it has '0' at the beginnig then it will be sorted by ascending for example.
CREATE TABLE #Test
(
col VARCHAR(10)not null primary key
)
INSERT INTO #Test VALUES ('A104')
INSERT INTO #Test VALUES ('A152')
INSERT INTO #Test VALUES ('A1010')
INSERT INTO #Test VALUES ('A15')
INSERT INTO #Test VALUES ('A17')
INSERT INTO #Test VALUES ('AA130')
INSERT INTO #Test VALUES ('B11')
INSERT INTO #Test VALUES ('B30')
SELECT * FROM #test ORDER BY
SUBSTRING (col, 0,PATINDEX('%[0-9]%',col))+RIGHT('00000' + SUBSTRING (col,
PATINDEX('%[0-9]%',col) , LEN(col)),5)
Tuesday, March 6, 2007
Subscribe to:
Post Comments (Atom)
1 comment:
Post a Comment