How Can I Make Oracle Query Sort Order Dynamic?

后端 未结 3 2024
你的背包
你的背包 2021-01-23 17:23

I have a Oracle procedure inside a package like this

PROCEDURE getEmployee
(
  pinLanguage               IN    VARCHAR2,
  pinPage                   IN    NUMBER         


        
3条回答
  •  爱一瞬间的悲伤
    2021-01-23 18:10

    You can use separate order by for asc and desc as following:

    ORDER BY 
    CASE pinSortOrder WHEN 'asc' THEN
        CASE pinSortColumn 
          WHEN 'FullName' THEN FULL_NAME 
          WHEN 'DateOfBirth' THEN to_char(DATE_OF_BIRTH,'yyyymmddhh24miss')
          WHEN 'Gender' THEN GEN_TR.GENDER   
        END
    END,
    CASE pinSortOrder WHEN 'desc' THEN
        CASE pinSortColumn 
          WHEN 'FullName' THEN FULL_NAME 
          WHEN 'DateOfBirth' THEN to_char(DATE_OF_BIRTH,'yyyymmddhh24miss')
          WHEN 'Gender' THEN GEN_TR.GENDER   
        END
    END DESC
    

    Let's say you have passed pinSortColumn as FullName and pinSortOrder as asc then order by clause will be ORDER BY FULL_NAME, NULL DESC (please note that default order will be asc so I have not write it in the code. Query will be ordered by FULL_NAME in ascending manner)

    Now, If you have passed pinSortColumn as FullName and pinSortOrder as desc then order by clause will be ORDER BY NULL, FULL_NAME DESC.

    Null will not impact ordering.

    I hope it is clear now.

    Cheers!!

提交回复
热议问题