Sorting

Hi,

is it possible to use variable for sorting?

Something like:

declare @sort varchar(10)
SET @sort='column1 DESC'

SELECT ROW_NUMBER() OVER (ORDER BY @sort)AS rowId, * FROM table

Is dynamic SQL only option?

Thank you,
Simon
0
simon
4/15/2010 10:28:16 AM
sqlserver.programming 1873 articles. 0 followers. Follow

6 Replies
825 Views

Similar Articles

[PageSpeed] 10

On 15/04/2010 11:28, simon wrote:
> Hi,
>
> is it possible to use variable for sorting?
>
> Something like:
>
> declare @sort varchar(10)
> SET @sort='column1 DESC'
>
> SELECT ROW_NUMBER() OVER (ORDER BY @sort)AS rowId, * FROM table
>
> Is dynamic SQL only option?

You can use CASE to help you order dynamically.

Here is one I use:

ORDER BY
CASE @sort WHEN 1 THEN sdl_item END ASC,
CASE @sort WHEN 3 THEN sor_orderdate END ASC,
CASE @sort WHEN 5 THEN sdl_despatch END ASC,
CASE @sort WHEN 2 THEN sdl_item END DESC,
CASE @sort WHEN 4 THEN sor_orderdate END DESC,
CASE @sort WHEN 6 THEN sdl_despatch END DESC

Its used on a webpage with a drop down box, the value determines the 
type of sort and its direction.

If all the sort columns were of the same type you can cut it down to 
just 2 CASE's, one for ASC and one for DESC, but if you have mixed 
types, like datetime and varchar then you need one CASE per sort type.

Dooza
0
Dooza
4/15/2010 10:48:55 AM
Simon
No, use CASE expression
ORDER BY CASE WHEN @sort = 'col1' AND @dir = 1 THEN col1 END ASC,
         CASE WHEN @sort = 'col1' AND @dir = 0 THEN col1 END DESC,
         CASE WHEN @sort = 'col2' AND @dir = 1 THEN col2 END ASC,
         CASE WHEN @sort = 'col2' AND @dir = 0 THEN col2 END DESC




"simon" <zupan.net@gmail.com> wrote in message 
news:a0eb3a56-f273-461a-b941-59be598d19f9@12g2000yqi.googlegroups.com...
> Hi,
>
> is it possible to use variable for sorting?
>
> Something like:
>
> declare @sort varchar(10)
> SET @sort='column1 DESC'
>
> SELECT ROW_NUMBER() OVER (ORDER BY @sort)AS rowId, * FROM table
>
> Is dynamic SQL only option?
>
> Thank you,
> Simon 


0
Uri
4/15/2010 11:19:19 AM
On 15 apr., 13:19, "Uri Dimant" <u...@iscar.co.il> wrote:
> Simon
> No, use CASE expression
> ORDER BY CASE WHEN @sort =3D 'col1' AND @dir =3D 1 THEN col1 END ASC,
> =A0 =A0 =A0 =A0 =A0CASE WHEN @sort =3D 'col1' AND @dir =3D 0 THEN col1 EN=
D DESC,
> =A0 =A0 =A0 =A0 =A0CASE WHEN @sort =3D 'col2' AND @dir =3D 1 THEN col2 EN=
D ASC,
> =A0 =A0 =A0 =A0 =A0CASE WHEN @sort =3D 'col2' AND @dir =3D 0 THEN col2 EN=
D DESC
>
> "simon" <zupan....@gmail.com> wrote in message
>
> news:a0eb3a56-f273-461a-b941-59be598d19f9@12g2000yqi.googlegroups.com...
>
>
>
> > Hi,
>
> > is it possible to use variable for sorting?
>
> > Something like:
>
> > declare @sort varchar(10)
> > SET @sort=3D'column1 DESC'
>
> > SELECT ROW_NUMBER() OVER (ORDER BY @sort)AS rowId, * FROM table
>
> > Is dynamic SQL only option?
>
> > Thank you,
> > Simon- Skrij navedeno besedilo -
>
> - Prika=BEi citirano besedilo -

As I thought. Order by case is usually much slower than create dynamic
sql.
So, I'll stay with dynamic sql.

thanks, S
0
simon
4/15/2010 11:27:28 AM
simon
> Order by case is usually much slower than create dynamic
>sql.

Hmm, can you provide me with  your test script??


"simon" <zupan.net@gmail.com> wrote in message 
news:f31833f6-cf4a-4f5e-8c79-796d899a661e@u34g2000yqu.googlegroups.com...
On 15 apr., 13:19, "Uri Dimant" <u...@iscar.co.il> wrote:
> Simon
> No, use CASE expression
> ORDER BY CASE WHEN @sort = 'col1' AND @dir = 1 THEN col1 END ASC,
> CASE WHEN @sort = 'col1' AND @dir = 0 THEN col1 END DESC,
> CASE WHEN @sort = 'col2' AND @dir = 1 THEN col2 END ASC,
> CASE WHEN @sort = 'col2' AND @dir = 0 THEN col2 END DESC
>
> "simon" <zupan....@gmail.com> wrote in message
>
> news:a0eb3a56-f273-461a-b941-59be598d19f9@12g2000yqi.googlegroups.com...
>
>
>
> > Hi,
>
> > is it possible to use variable for sorting?
>
> > Something like:
>
> > declare @sort varchar(10)
> > SET @sort='column1 DESC'
>
> > SELECT ROW_NUMBER() OVER (ORDER BY @sort)AS rowId, * FROM table
>
> > Is dynamic SQL only option?
>
> > Thank you,
> > Simon- Skrij navedeno besedilo -
>
> - Prika�i citirano besedilo -

As I thought. Order by case is usually much slower than create dynamic
sql.
So, I'll stay with dynamic sql.

thanks, S 


0
Uri
4/15/2010 11:39:26 AM
I used to use CASE statement in JOIN, WHERE or ORDER BY statements.
Then I found out that
almost always execution times where much faster(even 5 times) if I
rewriten sql statement without case statements and execute it as
dynamic sql.
The more case statements I had, the faster execution time was with
dynamic sql compered to case statements.
Since than I use always dynamic sql instead of case statements. It was
newer slower than sql with case.

I don't have test script at the moment. You think that there are some
cases where CASE is faster?

thank you for your help,
Simon
0
simon
4/15/2010 12:02:01 PM
simon
I have benchmarked this situation as I try to use dynamic sql as a last 
resort. It also depends on what indexes do you have a  take a look into a 
execution plan to compare performance




"simon" <zupan.net@gmail.com> wrote in message 
news:f1bd56b2-09f1-41db-8593-71579d6b5711@x12g2000yqx.googlegroups.com...
>I used to use CASE statement in JOIN, WHERE or ORDER BY statements.
> Then I found out that
> almost always execution times where much faster(even 5 times) if I
> rewriten sql statement without case statements and execute it as
> dynamic sql.
> The more case statements I had, the faster execution time was with
> dynamic sql compered to case statements.
> Since than I use always dynamic sql instead of case statements. It was
> newer slower than sql with case.
>
> I don't have test script at the moment. You think that there are some
> cases where CASE is faster?
>
> thank you for your help,
> Simon 


0
Uri
4/15/2010 12:08:15 PM
Reply:

Similar Artilces:

Where's the Sort by New Message option?
Not sure when the layout of the newsgroups changed but I can't seem to find the ability to sort by new message in a thread instead of sorting by just the original thread date. That was hugely helpful as I could follow along and see what threads were still active. If you're gonna hang around in the newsgroups (any newsgroups), you may want to start using a newsreader. Microsoft Outlook Express can do it for you. Saved from a previous post: You may want to connect to the ms newsserver directly: If you have Outlook Express installed, try clicking on these links (or copy and paste i...

How to sort account list?
I'm using MS Money 2004 Small Business. In the account list, my accounts are catagorized by and in this order: - bank accounts - credit accounts - investment accounts - loans and liabilities - asset accounts TOTAL BALANCE In the above view, I cannot easily determine totals for assets and liabilities. The following view does this. - bank accounts - investment accounts - asset accounts SUBTOTAL -loans and liabilities SUBTOTAL TOTAL BALANCE How do I get the above view? Thanks, Brett I don't use Small Business. But you can run a Net Worth report to get total assets and ...

Sorting
Hi, is it possible to use variable for sorting? Something like: declare @sort varchar(10) SET @sort='column1 DESC' SELECT ROW_NUMBER() OVER (ORDER BY @sort)AS rowId, * FROM table Is dynamic SQL only option? Thank you, Simon On 15/04/2010 11:28, simon wrote: > Hi, > > is it possible to use variable for sorting? > > Something like: > > declare @sort varchar(10) > SET @sort='column1 DESC' > > SELECT ROW_NUMBER() OVER (ORDER BY @sort)AS rowId, * FROM table > > Is dynamic SQL only option? You can use CASE to he...

Row names will not move with sort
Each row in my summary table in Sheet1 is hyperlinked to a corresponding table in Sheet2 with additional details. I need to move the rows in my summary table (Sheet1) and preserve the links to and from the details tables (Sheet2). I found that I can move rows in Sheet1 with cut & insert and the hyperlinks are maintained. I can travel from a row in summary table (Sheet1) to details table (Sheet2) and back, even after the corresponding row (Sheet1) was moved. But if I sort the rows in Sheet1 the links from Sheet2 back to corresponding rows in Sheet1 lead to presorted locations. Apparen...

sorts not sorting
OK- Thanks to everyones help I now i have a list i can work with... but there are a few problems.... the zips are all 5 digit and now i have to sort them... the problem is, THEY WONT SORT CORRECTLY!!!!!!! The numbers are not in order... some are but a lot are not... is there anyway to fix this???? i need to sort them by zip code but cant seem to get them to do it correctly.. any ideas??? ------------------------------------------------ ~~ Message posted from http://www.ExcelTip.com/ ~~ View and post usenet messages directly from http://www.ExcelForum.com/ You are going to be far better of...

import- number- sort?
I imported this data into a spread sheet- I tried to format it to number, but when I sort it- I get : 37.08 4.33 4.79 4.8 42.56 5.94 Whats up with this? Thanks Brent Hi Brent, Install the TrimAll macro, select the column and invoke the macro from Alt+F8 http://www.mvps.org/dmcritchie/excel/join.htm#trimall Directions to install and use a macro at http://www.mvps.org/dmcritchie/excel/getstarted.htm#havemacro I expect that you have spaces or CHAR(128) "Required Blank" characters in you data you can check is =LEN(A1) --- HTH, David...

sorting macro #3
I need to sort on 8 cells in a row and on 1500+rows. I can do it one at a time but I know there must be an easier way. Can ANYONE HELP? C3:J3 I need these cells sorted and then down to C1532:J1532 I did create a macro to sort after I selected them but still one at a time. Does it have to be a macro? I can edit a macro but don't really know how to program them. Yes, it has to be a macro. The following should do it. This macro loops through all the entries in Column C, and in each row it sorts the values in Columns C:J. HTH Otto Sub SortRows() Dim rColC As Range Dim i As...

Can we sort a form and also be able to enter new records.
Hi, It is possible to sort the data on a form and also be able to enter new and edit the existing records in it. Cheers! On Tue, 15 Jan 2008 15:41:16 -0800 (PST), Rex wrote: > Hi, > > It is possible to sort the data on a form and also be able to enter > new and edit the existing records in it. > > Cheers! I assume you mean "Is it". The form sort order has nothing to do with editing or adding new records, so the answer is yes. If you cannot edit or add new records, make sure the form's record source, if it is a query, is updateable. Some queries are not. O...

using addrress books to sort incoming mail
I use address books to sort incoming mail. An odd thing: depending on how the sender's name comes across, it doesn't get caught by the filter (amd moved to the "Family Mail" Folder I have set up. for example: my mom and dad's email (from momanddad@somedomain.com) comes as from that address. However, in my contacts, they are listed by their names: John and Mary Smith, with momanddad@somedomain.com as their email address and John and Mary Smith as the display name. What have I done wrong? TIA 1. The big ONE - failed to post your version of Outlook. Rules operate at ...

Sorting checking register
How do i sort my check register in Money 2004 Deluxe so that uncleared transactions appear below cleared transactions? In Quicken i could click on the column to provide that sort. In microsoft.public.money, Dean wrote: >How do i sort my check register in Money 2004 Deluxe so >that uncleared transactions appear below cleared >transactions? In Quicken i could click on the column to >provide that sort. You don't. Available choices are chosen by clicking View at the top of the register. ...

Unmerge so I can sort
I coy/pasted data into Excell and when I try to sort it I get "This operation requires merged sells to be identically sized". I understadn the work around in KB but how do I find which sells are merged? I wouldn't bother looking. I'd just remove all the merged cells from the range to sort. Select that range format|cells|alignment tab uncheck the merge cells box But if you wanted to search, you can do it via process of elimination. Select a range, format|cells|alignment tab. If that merge cells box is checked, then the whole selection is merged. If it's grey, t...

sorting issue
Hi, When a range of columns are highlighted and a sort is performed on only one column empty cells above the sort display first. How can this be prevented. I know when there is data in any of the other column but not on the column being sorted this will happen. Any thoughts? Pat Are you sure the cells are really empty? They don't contain spaces or even formulas that evaluate to "". (Even formulas converted to values that returned "")? Pat wrote: > > Hi, > > When a range of columns are highlighted and a sort is performed on only one > column em...

Sort not sorting all rows
I'm using Excel 2000. have created a document, uploaded it to google docs and spreadsheets, exported it as a doc, converted it to a spreadsheet (excel) and uploaded it again to google docs. It's not a complicated file - no calculations or anything, just a simple log to enable us to collaborate on change requests and website faults. New requests are assigned a number incrementally one higher than the previous. So we need to sort on the Log number column to see what the last logged number was. However, it sorts most of the spreadsheet and leaves the same 5 rows unsorted at the...

Sort and exclude certain words
Hi ... I work in a public library and frequently export lists of books from our online catalog to Excel, so that I can manipulate the data in various ways. My problem in sorting in Excel is this: Our library catalog excludes words like "The" "A" or "An" at the beginning of a title when sorting. Excel, however, does not. Is there any way I can sort on a field in Excel and have it ignore certain words at the beginning of a string? Thanks! -- jds217 ------------------------------------------------------------------------ jds217's Profile: http://www.exc...

Sort date by day and not year
Need to sort birthdates by month and day; ignore year. Ex: Would like to sort like list below: 3/02/1997 3/15/2002 3/21/1996 Not like this: 3/21/1996 3/02/1997 3/15/2002 Please help and thank you for your help. Kathy Hi one way: - add an additional helper column (lets ay B) - insert the following formula in B1 (if column A stores your list): =MONTH(A1) - copy this formula for all rows - sort with this helper column -- Regards Frank Kabel Frankfurt, Germany Kathy wrote: > Need to sort birthdates by month and day; ignore year. > > Ex: > Would like to sort like list below: >...

Not sorting as expected
I have a database some 10 columns wide and 1200 rows deep. When I sort by one particular column it sorts BLANKS before text meaning that the data appears at the bottom of the database although still in alphabetical order. I have the formatting set to GENERAL for the whole column and do want the blank cells. None of the other columns do this. I am totally perplexed as I thought Excel sorted blanks nearer the end of it's priority. I have tried formatting the column to TEXT and even NUMBER also but it still makes the data appear at the bottom of the table. This doesn't make any se...

sort without the sort button
Hi all. I have a table of strings that I have concatenated from several dro down lists. I now need to sort this data into a single column alphabetically and list all unique entries along with a percentage. I think I can do the listing unique entries etc. if I can just sort ou the problem I am having with sorting a column alphabetically. The problem is that I want to be able to use cell formulas to do th sorting as I want the sheet 'idiot proof'. The only user intervention want is for them to initially select the data they use from the dro down lists. I can do this using macro'...

Sorting...
I am trying to sort a csv list. The first column is a date & the 2nd is time. Can I merge these 2 together, so I can get date & time together, allowing me to sort based on that? If they're really dates and times, you could just use a helper cell and then use a formula like: =a1+b1 You can give it a nice format showing date and time if you like. But why not just sort the list using the date as the primary key and the time as a secondary key? Mike wrote: > > I am trying to sort a csv list. > The first column is a date & the 2nd is time. > Can I merge these 2 ...

Ranking
I previously revived a formula (Thanks Max) to Sort and Rank my Stores by the Strongest Store to the Lowest Store. It did exactly what it was supposed to do with my sample layout I made with just Four stores and scores. But when I added all 14 stores to the list (each store as a rank like 2.45 or 3.56 or 11.75) it will not sort them properly. I am using =IF(ISNA(RANK(Q7,Q7:Q20,1)),"",INDEX(O7:O20,RANK(Q7,Q7:Q20,1))) for the ranking system. It works when the stores Ranks are SINGLE digit numbers, but when they go into the tenths or hundredths the formula can't ...

Sort range changes during sort
After highlighting the columns and rows I want sorted, I select data and sort. At this point the sort range changes to include the entire row from A to IV of each row I selected. I've searched the options screen and help menu, but don't know why this is happening. Thanks in Advance. This is a complete guess--I couldn't duplicate what happened to you in xl2003. Do you have merged cells in that range? If yes, maybe that's the problem. coffedrinker2003 wrote: > > After highlighting the columns and rows I want sorted, I select data and > sort. At this point the so...

sort equal groups of data
hi, i need a help in this, plz i got this list, id like to check the common fields (in 2 and 3 columns) like this, p.ex (so later, i could delete them, and keep and analize the other groups of data) LG-0060-0703 MT 6 LG-0060-0703 CX 6 LG-0060-0703 MT 1 LG-0060-1003 MT 6 LG-0060-1003 CX 6 LG-0060-1003 MT 1 LG-0060-1203 MT 6 LG-0060-1203 CX 6 LG-0060-1203 MT 1 LG-0060-2003 MT 6 LG-0060-2003 CX 6 LG-0060-2003 MT 1 LG-0060-3003 MT 6 LG-0060-3003 CX 6 LG-0060-3003 MT 1 LG-0060-4003 MT 6 LG-0060-4003 CX 6 LG-0060-4003 MT 1 LG-0100018 UN 1 i appreciate your help thanks Not certain what...

How do I sort for the maximum values in each year in excel?
How do I sort data so I can see (sort?) the maximum value for each year in excel. I have 365 values per year and 78 years worth of data. I got excel to sort each year from greatest value to smallest, but now I want to sort it so each years max value is shown first, then the next years max value, etc. You would need extra help columns with formulas or using a filter if you apply auto filter and select the year from the year column and then copying the result somewhere else, then do the sorting base on the value descending. There is now way the built in sort can handle it in one fell swoop ...

Entourage contact sorting
Entourage 2008 for mac. =A0I am trying to sort my contacts by category and then by last name...any thoughts? On 2010-01-22 20:39:09 -0800, shar-shar said: > Entourage 2008 for mac. �I am trying to sort my contacts by category > and then by last name...any thoughts? Unfortunately, Entourage does not allow sorting by one field and sorting within that grouping by a second field. Just one field at a time. -- Allen Watson MVP for Office (Entourage, Word) http://homepage.mac.com/allen_a_watson/ HELP for Entourage: http://entourage.mvps.org On 1/22/10 8:39 PM, in article...

Sorting in Excel
I have a lot of data with three different groups represented by three different numbers. Is there any way to sort them by groups instead of going through by hand counting one by one? Thanks for all your help. Give us an example of the data (Don't attach any files though), showing us what you have and what you want. -- Regards Ken....................... Microsoft MVP - Excel Sys Spec - Win XP Pro / XL2K & XLXP ---------------------------------------------------------------------------- Attitude - A little thing that makes a BIG difference ----...

ascending sort definition [sorting alphabetically]
Does ascending sort mean A-Z? Yes. Cordially, Chip Pearson Microsoft MVP 1998 - 2010 Pearson Software Consulting, LLC www.cpearson.com [email on web site] On Tue, 5 Jan 2010 17:44:02 -0800, GaryBlade <GaryBlade@discussions.microsoft.com> wrote: >Does ascending sort mean A-Z? Yes. See http://www.exceltip.com/st/How_Excel_Sorts_Lists/246.html for more information. "GaryBlade" wrote: > Does ascending sort mean A-Z? ...