tags:

views:

39

answers:

3

How can I add ELSE clause to the following code?

 ROW_NUMBER() OVER (ORDER BY 
    CASE WHEN @OrderByColumn='ViewCount' AND @OrderDirection=0 THEN docsT.ViewCount END ASC,    
    CASE WHEN @OrderByColumn='AddedDate'AND @OrderDirection=0 THEN docsT.AddedDate END ASC,
    CASE WHEN @OrderByColumn='AddedBy'AND @OrderDirection=0 THEN docsT.AddedBy END ASC,  
    CASE WHEN @OrderByColumn='Title' AND @OrderDirection=0 THEN docsT.Title  END ASC
) AS RowNum
A: 

Just add something that will always evaluate to true at the end.

I don't know what your requirements are, so I am guessing the ORDER BY:

 ROW_NUMBER() OVER (ORDER BY 
    CASE WHEN @OrderByColumn='ViewCount' AND @OrderDirection=0 THEN docsT.ViewCount END ASC,    
    CASE WHEN @OrderByColumn='AddedDate'AND @OrderDirection=0 THEN docsT.AddedDate END ASC,
    CASE WHEN @OrderByColumn='AddedBy'AND @OrderDirection=0 THEN docsT.AddedBy END ASC,  
    CASE WHEN @OrderByColumn='Title' AND @OrderDirection=0 THEN docsT.Title  END ASC,
    CASE WHEN 1 = 1 THEN docsT.Title END ASC
) AS RowNum
Oded
It will probably be the same to change the second to last line into: "docsT.Title ASC"
hongliang
A: 

There are many ways: you could wrap the entire case in an IsNull(...,docsT.Title). Or you could use the ELSE clause, like:

CASE WHEN OrderDirection = 0 THEN
    CASE @OrderByColumn
    WHEN 'ViewCount' THEN docsT.ViewCount
    WHEN 'AddedDate' THEN docsT.AddedDate
    WHEN 'AddedBy'   THEN docsT.AddedBy
    ELSE docsT.Title
    END
ELSE docsT.Title
END
Andomar
+1  A: 

You can put the order in an outer case, and then for selecting the field you can use the form of the case where you compare one value to several values. To support ascending and descending sort, you have to repeat it all again.

order by
  case when @OrderDirection = 0 then
    case @OrderByColumn
      when 'ViewCount' then docsT.ViewCount
      when 'AddedDate' then docsT.AddedDate
      when 'AddedBy' then docsT.AddedBy
      when 'Title' then docsT.Title
      else docsT.Title
    end
  end asc,
  case when @OrderDirection = 1 then
    case @OrderByColumn
      when 'ViewCount' then docsT.ViewCount
      when 'AddedDate' then docsT.AddedDate
      when 'AddedBy' then docsT.AddedBy
      when 'Title' then docsT.Title
      else docsT.Title
    end
  end desc
Guffa
+1 Right! I thought @OrderDirection had something to do with being a seller or a buyer :)
Andomar