In my database, I have a column which can contain either only numbers, or text (which can also contain numbers). For char
columns, SQL server sorts value by character code (1, 12, 14, 2, 20, 200, 3, 30, ...).
How would I have to write my .OrderBy
statement to sort them like numerics, when they are numeric?
2条答案
按热度按时间x7yiwoj41#
If you want to sort on DB ( not on application ), then
use
patindex()
andsubstring()
functions to extract the integer part of your column( considering null cases as zero ), and then cast as integer :within your select statement.
Demo
v8wbuo2f2#
How about this SQL:
See also: How do I sort a VARCHAR column in SQL server that contains numbers?
I used the following C# snippets in order to get this behavior:
DataContext:
MyEntity:
Linq query: