I'm a database beginner. I'm discovering parameters. Gosh, they're fun.

Is it possible to have a resultset sorted ascending or descending, depending on a Boolean parameter? Like:

SELECT name, size from ANIMALs
[...]
ORDER BY size :asc_or_desc

It's clear I can't just pass a String "ASC" or "DESC" in there. I suspect I'm going to need some "IF"-condition. Maybe it's even possible to split retrieving and sorting up into two separate statements. Can somebody give me a hand?

Many thanks in advance.

asked 10 Sep '14, 01:46

Overclock%20Your%20Breakfast's gravatar image

Overclock Yo...
1157916
accept rate: 0%


One possibility is this:

TRY DROP TABLE #Temp; CATCH ALL END TRY;

SELECT name, size 
INTO #Temp
FROM ANIMALs

IF :SORT_ASCENDING THEN
  SELECT * FROM #Temp ORDER BY size;
ELSE
  SELECT * FROM #Temp ORDER BY size DESC;
END IF;

It uses a temporary table #Temp to store the data which can be a problem for performance reasons.

You can of course put the whole statement into the IF and ELSE blocks, but you'd have to maintain the statement twice:

IF :SORT_ASCENDING THEN
  SELECT name, size 
  FROM ANIMALs
  ORDER BY size;
ELSE
  SELECT name, size 
  FROM ANIMALs
  ORDER BY size DESC;
END IF;
link

answered 10 Sep '14, 02:59

Jens%20M%C3%BChlenhoff's gravatar image

Jens Mühlenhoff
1.3k51037
accept rate: 18%

Your answer to the original question.
If responding to a request for additional information, please edit the question or use the comment functionality.
toggle preview

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Markdown Basics

  • *italic* or _italic_
  • **bold** or __bold__
  • link:[text](http://url.com/ "Title")
  • image?![alt text](/path/img.jpg "Title")
  • numbered list: 1. Foo 2. Bar
  • to add a line break simply add two spaces to where you would like the new line to be.
  • basic HTML tags are also supported

Tags:

×325
×172
×133

Asked: 10 Sep '14, 01:46

Seen: 2,688 times

Last updated: 10 Sep '14, 02:59

Advantage Developer Zone Contact Us Privacy Policy Copyright Info


Powered by Advantage Database Server and OSQA
Disclaimer: Opinions expressed here are those of the poster and do not necessarily reflect the views of the company.