Skip to content
Advertisement

T-SQL sort integer values

I’d like to create a procedure which later will have 5 integer parameters as an input. Within these procedure I want to sort those integer values in ascending order and later update a table. I did it with case whens so that I don’t lose the information of each parameter (Background: Additional to this, each parameter is connected to a string which I need so sort in the same order. But sorting those integer first is faster.)

Somehow I can’t get the sorting for the middle part. Min and Max Value works fine:

Can someone give a hint for the middle part?

Advertisement

Answer

I don’t know exactly how you want to use the sorted integers, but why not let SQL do the sorting for you? the below, creates a temp table (@s), with the five integers (passed in as parameters?) in it and sorts them.

What you do in the stored proc with this sorted list is another question…

Ok, here’s a script to try and work through. It is T-SQL. Please run it and look at the output. the first part creates a dummy table To represent your table and populates it with some data. It assumes that your table has an integer Primary Key.

The next part is the script that generates the extra ten columns from the data in this sample table (`sortTbl’). It works even if the original values are not only 1 through 5, but within each row there should not be duplicates.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement