I’m writing a function and I wanted to paste a list typed by user to filters in WHERE. List typed to function by user:
filters = list( ‘fruits’ = c(‘apple’,’orange’),
‘vegetables’ = ‘carrot’)
How to paste this list to sql query in glue sql:
df = glue_sql(“select …
where filters)
CodePudding user response:
parts <- paste(sapply(names(filters), function(nm) sprintf("%s in ({%s*})", nm, nm)), collapse = " and ")
parts
# [1] "fruits in ({fruits*}) and vegetables in ({vegetables*})"
glue::glue_data_sql(filters, paste("select * from table where", parts), .con = con)
# <SQL> select * from table where fruits in ('apple', 'orange') and vegetables in ('carrot')