Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Dynamic SOQL + var binding
Set<String> names = new Set<String>{'Me','Myself','I'};
String query = 'SELECT id, name FROM User WHERE LastName IN :names';
List<sObject> objs = Database.query(query);
System.debug(objs);
@kevinohara80

This comment has been minimized.

Copy link

@kevinohara80 kevinohara80 commented Jun 19, 2012

How is this possible? That set variable is private and the query variable is just a String. I believe you, but this makes no sense.

@capeterson

This comment has been minimized.

Copy link
Owner Author

@capeterson capeterson commented Jun 19, 2012

A coworker wrote it and I was reviewing his code. My conclusion is that this is some form of black magic.

Or a more serious answer: Database.query must use some reflection-like magic under the hood to find any variable mentioned that's in scope at the time of the query and load it in.

@texastoland

This comment has been minimized.

Copy link

@texastoland texastoland commented Jun 20, 2012

Voodoo if you ask me ;) Technically it's an interpreted language right? No idea how it works with byte code though.

@kevinohara80

This comment has been minimized.

Copy link

@kevinohara80 kevinohara80 commented Jun 20, 2012

Actually, the platform now complies to Java bytecode. This is a fairly recent change.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment