generate where clause in bash using variables

强颜欢笑 提交于 2020-07-03 15:54:51

问题


I have some variables in bash like below.

min_date='2020-06-06'
max_date='2020-06-08'
max_seq_min_date=1  --This is till where data is processed
max_seq_max_date=3  --This is till where data has to be processed

batch_date is the column where I will use the min and max_date values

For each date there will be 4 sequences

I want to generate a where clause that I can use in sql query

Now I want to generate a where clause that looks like below

WHERE 1=1 or (batch_date = '2020-06-06' and seq_num in ('2','3', '4')) 
or (batch_date = '2020-06-07' and seq_num in ('1','2','3','4'))
or (batch_date = '2020-06-08' and seq_num in ('1','2','3'))

How can i achieve what I want?


回答1:


It will be more efficient to make minor changes to the query - making it easier to generate (equivalent) SQL dynamically.

It uses "between" operator to avoid variable length lists for the 'in (...)' conditions.

Note comment about 1=1, it is kept as per question, but need to be reviewed, as it will always make the condition pass.

min_date='2020-06-06'
max_date='2020-06-08'
max_seq_min_date=1
max_seq_max_date=3

echo "
WHERE 1 = 1 or case
    when batch_date = '$min_date' then seq_num between 1 and $max_seq_min_date
    when batch_date = '$max_date' then seq_num between 1 and $max_seq_max_date
    when batch_date between '$min_date' and '$max_date' then seq_num between 1 and 4
    else false
    end
" 

I do NOT have mysql, but the above works for Postgresql.




回答2:


Just use interpolation, i.e.

sql_clause="... batch_date = '$min_date' and seq_num in ('2','3', '4') ...."


来源:https://stackoverflow.com/questions/62292634/generate-where-clause-in-bash-using-variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!