tags:

views:

213

answers:

3

Hi, All! I'm want use $ macro in groovy GString. When i'm wrote this code

['cdata','tdata'].each { def sql = "select * from $it_1" }

i'm get error unknown property $it_

ok, i'm rewrite it

['cdata','tdata'].each { def sql = "select * from ${it}_1" }

then i'm get unwanted quotes in result string - "select * from 'cdata'_1"

Question is how i'm can use $-macro in GString to achive "select * from cdata_1" result string?

A: 
groovy:000> ['cdata','tdata'].each { def sql = "select * from ${it}_1"; println sql }
select * from cdata_1
select * from tdata_1
===> [cdata, tdata]

I dont see any quotes... that is why I was asking for clarification

Aaron Saunders
Hm... really... very strange... I'm using Eclipse with Groovy Plugin and run as Groovy Script. May be problem there... I'm try in groovy console and you right, i'm don't get quotes.
Alexey Sviridov
+1  A: 

If the quotes are not from your IDE, or whatever you're evaluating your code in, you can do this:

['cdata','tdata'].each { def sql = "select * from ${it.replaceAll("'","")}_1" }
Geo
I'm using Eclipse with Groovy Plugin and run as Groovy Script. May be problem there... But i'm try your solution, not so elegant but do work.
Alexey Sviridov
+1  A: 

I think the issue here is that the groovy Sql class tries to be clever, and quote variables that are inserted into a GString at runtime (via $)

So printing it out, it will look ok, but when run through Sql, it will add the quotes as you have seen...

I think the solution here is to intern() the GString back into a String before you move on to the next step...

['cdata','tdata'].each { def sql = "select * from ${it}_1".intern() }
tim_yates
Not in this case, but i'm already explain GString in Sql.eachRow (for example) works different to GString in other places. I'm use "select * from $tableName" as String for solve this, else Sql create "select * from ?" and then using var tableName as parameter
Alexey Sviridov