Sorting a VARCHAR Column Containing Numbers in SQL Server
Sorting a VARCHAR column that contains a mix of letters and numbers can be challenging, especially when the desired order is numerical for numeric values.
Approach:
The recommended approach is to pad numeric values with a leading character to ensure they all have the same string length. This allows SQL Server to compare the values numerically.
Solution:
SELECT MyColumn FROM MyTable ORDER BY CASE ISNUMERIC(MyColumn) WHEN 1 THEN REPLICATE('0', 100 - LEN(MyColumn)) + MyColumn ELSE MyColumn END
In this query:
Example:
Consider a column named "MyColumn" with the following values:
Using the above query, the sorted results would be:
1 2 10 A B B1
The above is the detailed content of How to Sort a VARCHAR Column with Mixed Numbers and Letters in SQL Server?. For more information, please follow other related articles on the PHP Chinese website!