0

I need to create a dynamic SQL query that changes based on different arguments/variables existence and value:

So, I have something like this:

def create_query(user=None, max=None, list=None)

qs = 'SELECT N.status'

if user: 
    qs = qs.join('U.email')

qs = join('from notes as N)'

if user: 
  qs = 'LEFT JOIN users AS U on N.user_id=U.id'

if max:
  qs = qs.join('where max=') + max

if list:

  qs = qs.join('where fame_values in list')

....

I have around 20 variables that can change the query, so I'm looking for something more pythonic(like list comprehensions with conditions) but for strings

1
  • Do not do data concatenation like qs.join('where max=') + max since this is a security hole and will also impact application scalability. Use a bind variable instead. Commented Sep 5, 2018 at 1:07

2 Answers 2

1

You may create a function which create the query according to the arguments you pass to it.
Consider the following example:

def create_query(user, max_value = None):
    query = 'SELECT N.status'+ (' U.email' if user else ' ') + ' from notes as N' + (' LEFT JOIN users AS U on N.user_id=U.id' if user else ' ') + (' where max={}'.format(max_value) if max_value else " ") 
    return query

query = create_query(user=True,max_value=10)
# SELECT N.status U.email from notes as N LEFT JOIN users AS U on N.user_id=U.id where max=10
query = create_query(user=False)
# SELECT N.status  from notes as N 
query = create_query(user=True)
# SELECT N.status U.email from notes as N LEFT JOIN users AS U on N.user_id=U.id 
Sign up to request clarification or add additional context in comments.

Comments

0

if you are working with python , i suggest to build the query inside your code , and connects to the database with cx_Oracle (or other modules, if you have a different database)

if you really want to do it in pure sql, what you need to do is to preform a master join of everything , and use case to show the desired data you wish.

case when x then y
when b then c
else null end case1,
case2 when x then t
when g then c
else null end case2
from a join b join c join...

some examples for that exactly you wish to do will be helpful..

2 Comments

based on received arguments/variables I need to join none or up to 3 tables, and have multiple where clauses
you need to create all the 20 options of outcomes , and join them into 1 table in an inner join , so only the outcome that goes with the data will not be null, and just query that table , but for dynamic queryies , i would use python instead to query the data, it is much easier for more then 2-3 options..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.