0

How can I do this with an array? (without storing the array as regular variable)

VAR='String1 String2 String3'
SELECT * FROM db.table WHERE xy IN ( ${VAR// /, } );

not working example:

SELECT * FROM db.table WHERE xy IN ( ${ARRAY[@]// /, } );
1

The array expansion & replacement is working, but there are no spaces in your array elements. Compare with:

$ array=("one two" three four)
$ echo "${array[@]/ /, }"
one, two three four

You're trying to re-join the array elements with a comma & space (,) between them. I'll stealcopy one of glenn jackman's answers in this vein:

$ array=(String1 String2 String3)
$ joined=$( set -- "${array[@]}"; IFS=,; echo "$*" )

Then you can use:

SELECT * FROM db.table WHERE xy IN "$joined"

As an example:

$ array=("String1 String2" String3 String4)
$ joined=$( set -- "${array[@]}"; IFS=,; echo "$*" )
$ echo "$joined"
String1 String2,String3,String4

I don't know off-hand what you'll need to do to the SQL to quote array elements (Strings) that contain spaces (if any).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.