Note that there are some explanatory texts on larger screens.

plurals
  1. POSort string as number in sql server
    primarykey
    data
    text
    <p>I have a column that contains data like this. dashes indicate multi copies of the same invoice and these have to be sorted in ascending order</p> <pre><code>790711 790109-1 790109-11 790109-2 </code></pre> <p>i have to sort it in increasing order by this number but since this is a varchar field it sorts in alphabetical order like this</p> <pre><code>790109-1 790109-11 790109-2 790711 </code></pre> <p>in order to fix this i tried replacing the -(dash) with empty and then casting it as a number and then sorting on that</p> <pre><code>select cast(replace(invoiceid,'-','') as decimal) as invoiceSort...............order by invoiceSort asc </code></pre> <p>while this is better and sorts like this</p> <pre><code> invoiceSort 790711 (790711) &lt;-----this is wrong now as it should come later than 790109 790109-1 (7901091) 790109-2 (7901092) 790109-11 (79010911) </code></pre> <p>Someone suggested to me to split invoice id on the - (dash ) and order by on the 2 split parts</p> <p>like=====> <code>order by split1 asc,split2 asc (790109,1)</code> </p> <p>which would work i think but how would i split the column. </p> <p>The various split functions on the internet are those that return a table while in this case i would be requiring a scalar function.</p> <p>Are there any other approaches that can be used? The data is shown in grid view and grid view doesn't support sorting on 2 columns by default ( i can implement it though :) ) so if any simpler approaches are there i would be very nice.</p> <p><strong>EDIT</strong> : thanks for all the answers. While every answer is correct i have chosen the answer which allowed me to incorporate these columns in the GridView Sorting with minimum re factoring of the sql queries.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload