Forked from johncasimiro/Mimic SQL select * statement in SOQL using Apex
Created
June 15, 2018 10:55
-
-
Save cooljl31/2da44f90e74409e52c3b4db06f8dcaa6 to your computer and use it in GitHub Desktop.
A code snippet that mimics the popular Select * SQL syntax in force.com's Apex language.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* @description: A code snippet that mimics the popular Select * SQL syntax in force.com's Apex language. | |
*/ | |
// Initialize setup variables | |
String objectName = 'Contact'; // modify as needed | |
String query = 'SELECT'; | |
Map<String, Schema.SObjectField> objectFields = Schema.getGlobalDescribe().get(objectName).getDescribe().fields.getMap(); | |
// Grab the fields from the describe method and append them to the queryString one by one. | |
for(String s : objectFields.keySet()) { | |
query += ' ' + s + ', '; | |
} | |
// Manually add related object's fields that are needed. | |
query += 'Account.Name,'; // modify as needed | |
// Strip off the last comma if it exists. | |
if (query.subString(query.Length()-1,query.Length()) == ','){ | |
query = query.subString(0,query.Length()-1); | |
} | |
// Add FROM statement | |
query += ' FROM ' + objectName; | |
// Add on a WHERE/ORDER/LIMIT statement as needed | |
query += ' WHERE firstName = \'test\''; // modify as needed | |
try { | |
List<Contact> contacts = database.query(query); | |
} catch (QueryException e){ | |
//perform exception handling | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment