Reputation: 219
I have a table that has column name "BatchNo" and it contain both string and numeric values together. when i typed a select query i got following results.
i want to sort "BatchNo" column in following format
In my problem future batches may be have a,b,c .... letters with numeric values or only numeric values. how can i sort this column ? Hope you guys can help me to get some solution.
Upvotes: 2
Views: 1479
Reputation: 24046
try this:
SELECT *
FROM tableName
ORDER BY
CAST(LEFT(BatchNo, PATINDEX('%[^0-9]%', BatchNo + 'Z')-1) AS INT),
BatchNo
Upvotes: 1
Reputation: 18639
How about this:
SELECT *
FROM TABLE_NAME
ORDER BY CAST(LEFT(BatchNo, PATINDEX('%[^0-9]%', BatchNo + 'A')-1) AS INT)
Query works for a string which starts with numeric values only.
Upvotes: 0
Reputation: 263733
Why don't you alter the schema of your table into?
CREATE TABLE tableName
(
ShipmentNo INT,
ProjectCode VARCHAR(50),
BatchNo INT,
SubBatch INT,
.....
)
in this way, it is to sort the valkues the way you want.
follow-up question, is BatchNo
has only single character value from A-Z
, eg
11a
11b
and not
11aa
UPDATE 1
SELECT *
FROM tableName
ORDER BY CASE ISNUMERIC(batchNo)
WHEN 1 THEN batchNo
ELSE CAST(LEFT(batchNo, LEN(batchNo) - 1) AS INT)
END
Upvotes: 2