PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, December 4, 2022

[FIXED] How to create a dynamic where clause in Oracle (PL/SQL)

 December 04, 2022     oci8, oracle, plsql, sql     No comments   

Issue

I have the below query:

SELECT *
FROM FOO
WHERE LOCATION = :LOCATION
AND MY_DATE >= TIMESTAMP :BEGIN AND MY_DATE <= TIMESTAMP :END -- option 1 if :BEGIN & :END is not NULL
AND MY_DATE >= TIMESTAMP :BEGIN AND MY_DATE <= sysdate        -- option 2 if :BEGIN is not NULL & :END is NULL
AND MY_DATE <= TIMESTAMP :END                                 -- option 3 if :BEGIN is NULL & :END is not NULL
AND MY_DATE <= sysdate                                        -- option 4 if both :BEGIN & :END is NULL
ORDER BY MY_DATE;

so here :LOCATION is supplied by the user on code level using OCI8. For example:

require 'oci8'
cursor = conn.parse(query)
cursor.bind_param(':LOCATION', 'Chicago', String)

I only want one of the options from 1 to 4 to be part of the final query. For example if option 3 is true (:BEGIN is NULL & :END is not NULL) then the final query will be:

SELECT *
FROM FOO
WHERE LOCATION = :LOCATION
AND MY_DATE <= TIMESTAMP :END                                 -- option 3 if :BEGIN is not NULL & :END is NULL
ORDER BY MY_DATE;

Where user would supply an :END date

require 'oci8'
cursor = conn.parse(query)
cursor.bind_param(':LOCATION', 'Chicago', String)
cursor.bind_param(':START', NULL)
cursor.bind_param(':END', '2001-01-22 12:01:00', String)

and would result in:

SELECT *
FROM FOO
WHERE LOCATION = 'chicago'
AND MY_DATE <= TIMESTAMP '2001-01-22 12:01:00'
ORDER BY MY_DATE;

How do I write a query to allow this logic?


Solution

An option is to use CASE :

SELECT *
  FROM FOO
 WHERE LOCATION = :LOCATION
   AND MY_DATE >= CASE WHEN :BEGIN IS NOT NULL THEN :BEGIN
                       ELSE MY_DATE
                  END
   AND MY_DATE <= CASE WHEN :END IS NOT NULL THEN :END
                       ELSE SYSDATE
                  END
 ORDER BY MY_DATE;


Answered By - Gnqz
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing