0

I'm parametrizing a query in Scala.

I have an array of strings with column names named colNames.

I want to create an string where for each name of the string the output is A.colName = B.colName and then join all the items in the array putting an " AND " string between each item.

Example of input

val colNames = Array("colName1","colName2")
val table1 = "A"
val table2 = "B"

Example of the desired output

"A.colName1 = B.colName1 AND A.colName2 = B.colName2"

In a non FP language I would do that with a for loop, but I don't know how to do it in Scala in a functional way.

4
  • Are you using raw JDBC driver? How do you want to pair "A" with "colName1" and "B" with "colName2"? Commented Nov 21, 2022 at 11:49
  • @MateuszKubuszok I am passingg the raw query to the snowflake spark llibrary. A and B are the tables and i want to use them in a where condition where the columnName are equals Commented Nov 21, 2022 at 11:51
  • 3
    Then @Dogbert's answer should do the trick. (I wouldn't use infix notation though). Commented Nov 21, 2022 at 11:53
  • 1
    Whereever this piece of query ends up: make sure that the content of colNames is not controlled by the users, otherwise you'll quickly get requests along the lines of colNames = Array("colName1", "colName2 AND sendAllTehCoinzTo('BobbyTables') = 'success'"). Commented Nov 21, 2022 at 14:39

1 Answer 1

3

You can use the map and mkString methods on Array:

scala> colNames map { colName => s"${table1}.${colName} = ${table2}.${colName}" } mkString " AND "
val res0: String = A.colName1 = B.colName1 AND A.colName2 = B.colName2
Sign up to request clarification or add additional context in comments.

Comments

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.