More Conditional Sorting with SQL
November 10, 2004 Hey, Ted
Your tip “Conditional Sorting with SQL” is one cool tip! May I add two more examples?
My examples are in RPG, but I assume they will work with any language. In both examples, I use host variables to control the sort.
Host variable SortOption controls the sort in the first example. If host variable SortOption has a value of 1, the data is retrieved in order by customer name. If two customers have the same name, they are retrieved in customer number sequence. If SortOption has any other value, the data is retrieved in customer number sequence.
D SortOption S 1P 0 C/exec sql C+ C+ Declare C1 Cursor for C+ select cusnum, lstnam, init C+ from qiws/qcustcdt C+ order by C+ case when :SortOption = 1 C+ then lstnam C+ else digits(cusnum) end, C+ case when :SortOption = 1 C+ then cusnum C+ else 0 end C+ C/end-exec
In the second example, the data may be sorted by state, in either ascending or descending sequence. If host variable SortSeq has a value of A, the data is returned in ascending order by state. Within state, the data is sorted by last name and initials. A SortSeq value of D causes the states to be sorted in descending order, but the last name and initial fields are sorted in ascending order. If SortSeq has some other value, state is not used for sorting.
D SortSeq S 1A C/exec sql C+ C+ Declare C1 Cursor for C+ select state, lstnam, init from qiws/qcustcdt C+ order by C+ case when :SortSeq = 'A' then state else ' ' end, C+ case when :SortSeq = 'D' then state else ' ' end desc, C+ lstnam, C+ init C+ C/end-exec
–John
Thanks for the ideas, John. Several readers wrote in to say that they liked the tip, but none of them sent examples.
Using host variables to affect the behavior of SQL commands is one way to add flexibility to an application. For more information, see these articles from previous editions of this newsletter.
“Alternate SQL Row-Selection Criteria”
“Alternate SQL Row-Selection Criteria, Take 2”
–Ted