Kccrosser
1850 pts. | May 4 2009 8:29PM GMT
There is another way to do dynamic ordering. Create an additional result column to contain a sort code and populate that column with a string value based on the selection criteria, then use that column as the Order By column.
This isn’t hard, but requires some grunt work. It is easy enough to handle strings, but if you convert numeric values to strings they will sort oddly (”100″ comes before “2″).
For similar problems, my solution was to have functions that converted different numeric types to a string with leading zeros (within a reasonable range) so the resulting column sorted ok.
For multi-column sorting, you would need to write a function that took the argument string and for each row of result data, returned a concatenated string of the field data in the selected order, like in the following:
select …
, mySortFunction(order_arg, group_description_key, lpad(status_code, 4), to_char(num_field, ‘pattern’), …) as theSortColumn,
…
where
…
order by theSortColumn
MRDenny’s approach is much easier, but (particularly in older Oracles) often a compiled procedure query was far more efficient than running a dynamic sql query, so generating a sort column value was a lot less overhead. Note - This is only true when the result set of the query is substantially smaller than the source data (so you only call the function on a relatively small number of rows). If you are commonly returning a large portion of the source data, then generating the dynamic sql query is likely to be just as efficient.






