14 Sep 2006

Dynamic SQL Server ordering without using dynamic SQL.

For my current project I have a stored procedure that needs to sort data by 1 of 3 columns depending upon the option chosen by the user from the application.  This is only the dynamic part of the stored procedure, which also happens to be very complicated, so I didn’t wish to use dynamic SQL Server.  I know that within SQL server 2000 you can use a case against a variable to select which column to order the data by but the only caveat is that all the columns have to be the same data type.  My problem was that not all my columns are the same data type, I managed to over come this by using the new function within SQL server 2005 call Row_Number(), which gives a row number to each row, based upon the order by used within the over function, as this always returns the same data type it can be used within the case statement for the ordering. Below is an example of code:
1:DECLARE @vOrderby AS INT 
   2:  SET @vOrderby = 4
   3:   
   4:  SELECT TABLE_CATALOG , TABLE_SCHEMA , TABLE_NAME, COLUMN_NAME, ORDINAL_POSITION, COLUMN_DEFAULT, IS_NULLABLE, DATA_TYPE 
   5:  FROM information_schema.columns 
   6:  ORDER BY CASE @vOrderby  
   7:    WHEN 1 THEN ROW_NUMBER() OVER(ORDER BY TABLE_SCHEMA, TABLE_NAME) 
   8:    WHEN 2 THEN ROW_NUMBER() OVER(ORDER BY COLUMN_NAME) 
   9:    WHEN 3 THEN ROW_NUMBER() OVER(ORDER BY DATA_TYPE) 
  10:    WHEN 4 THEN ROW_NUMBER() OVER(ORDER BY ORDINAL_POSITION) 
  11:    WHEN 5 THEN ROW_NUMBER() OVER(ORDER BY IS_NULLABLE) 
  12:    WHEN -1 THEN ROW_NUMBER() OVER(ORDER BY TABLE_SCHEMA DESC , TABLE_NAME DESC ) 
  13:    WHEN -2 THEN ROW_NUMBER() OVER(ORDER BY COLUMN_NAME DESC ) 
  14:    WHEN -3 THEN ROW_NUMBER() OVER(ORDER BY DATA_TYPE DESC ) 
  15:    WHEN -4 THEN ROW_NUMBER() OVER(ORDER BY ORDINAL_POSITION DESC ) 
  16:    WHEN -5 THEN ROW_NUMBER() OVER(ORDER BY IS_NULLABLE DESC) 
  17:  END

I am not recommending this as a good solution, just a solution that might be useful for a small database.