Xplora
Xplora

Reputation: 903

Storing resultsets in single Array using Groovy/Grails

How do I store results for following queries in the same array using groovy?

select id from employee where employee_id=100
select id from employee where employee_id=200
select id from employee where employee_id=300

Example:

def calculate(employee_ids)
{
def result
Sql sql = new Sql(dataSource)

for (employee_id in employee_ids) {    
result = sql.rows("select id from employee where employee_id="+employee_id)
}

sql.close()

return result
}

Right now, 'calculate()' function just returns 300 when I pass 100, 200, 300 as 'employee_id'. ('employee_id' is in the form of an array)

How do I get aggregate result when I pass 100, 200, 300 etc. as 'employee_id' into a single array like [100,200,300]?

Thanks in advance!

Upvotes: 0

Views: 940

Answers (1)

Jeff Scott Brown
Jeff Scott Brown

Reputation: 27255

You haven't really provided enough information. It isn't clear how you are sending those queries to the database and that might end up being relevant. If you really need to send them separately then do that and combine the results with something like this...

def firstResult = // send query to db...
def secondResult = // send query to db...
def thirdResult = // send query to db...
def combinedResults = firstResult + secondResult + thirdResult

But maybe what you really want is to execute a query that is something like this...

select id from employee where employee_id in (100, 200, 300)

EDIT:

You could do something like this...

def result = []

for (employee_id in employee_ids) {
    result += sql.rows("select id from employee where employee_id=$employee_id").id
}

Upvotes: 4

Related Questions