Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save arufian/f3231cbda7bf87b7d4fe to your computer and use it in GitHub Desktop.
Save arufian/f3231cbda7bf87b7d4fe to your computer and use it in GitHub Desktop.
My version of "Select All Mimic2 in SOQL
global with sharing class CommonClass {
global List<Object> selectAllFromTable(String objectName, String whereCondition, String order, String limit1){
String query = selectAllQuery(objectName, whereCondition);
query += ' ORDER BY '+order+' LIMIT '+limit1;
try {
return database.query(query);
} catch (QueryException e){
//perform exception handling
System.debug('failed to selectAllFromTable');
System.debug('query: '+query+', tableName: '+objectName);
return NULL;
}
}
global List<Object> selectAllFromTable(String objectName, String whereCondition, String order){
String query = selectAllQuery(objectName, whereCondition);
query += ' ORDER BY '+order;
try {
return database.query(query);
} catch (QueryException e){
//perform exception handling
System.debug('failed to selectAllFromTable');
System.debug('query: '+query+', tableName: '+objectName);
return NULL;
}
}
global List<Object> selectAllFromTable(String objectName, String whereCondition){
String query = selectAllQuery(objectName, whereCondition);
try {
return database.query(query);
} catch (QueryException e){
//perform exception handling
System.debug('failed to selectAllFromTable');
System.debug('query: '+query+', tableName: '+objectName);
return NULL;
}
}
private String selectAllQuery(String objectName, String whereCondition){
/*
* @description: A code snippet that mimics the popular Select * SQL syntax in force.com's Apex language.
*/
// Initialize setup variables
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 + ', ';
}
// 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 '+whereCondition; // modify as needed
return query;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment