+ Start a Discussion
Linda 98Linda 98 

Help in building Dynamic soql

Below is the code with dynamic soql which fetches 5-6 records if no contact has level TOP and is fetching 3 records if they are TOP.(WHICH IS OK) 
but i want to fetch only 3 records if level is NOT TOP. but i am failing in building dynamic soql.How can i include LIMIT (already having LIMIT condition)?
String level='Top';
String query ='select id,custompicklist__c from contact';

if(Roleslist.size() >0){
    Set<String> roleSet = new Set<String>(Roleslist);
        for(Integer i= 0; i<Roleslist.size();i++){
            query +=' where account.Active__c=true and roles__c  INCLUDES (\''+Roleslist[0]+'\'';       
            query += ',\''+Roleslist[i]+'\'';
                query += ')';  //LIMIT 3 here does the work but it is giving me error for next condition.
        Boolean enforceLimit = false;
        if([SELECT count() FROM Contact WHERE  account.Active__c=true AND custompicklistfield__c=:level AND roles__c IN :roleSet LIMIT 1] > 0){
        query += ' AND custompicklistfield__c=:level';
        enforceLimit = true;
            query += ' LIMIT 3';
        if(query.contains(' INCLUDES ')){