[SalesForce] List at IN clause in Dynamic SOQl

I am fetching all the field from sObject and querying using Database.query().
When I query with List of id's it is throwing Invalid ID ('id', 'id', ...) error.

for example at static soql we can query with list of id's like below

select id, name from Account where id in:ids

but am getting error when i use in Dynamic SOQL.

Am using below code to fetch and query.

    List<id> ids = new List<id>();
    ids.add(...);
    List<Patient__c> paList;
        String query;
        String SobjectApiName = 'Patient__c';
        Map<String, Schema.SObjectType> schemaMap = Schema.getGlobalDescribe();
        Map<String, Schema.SObjectField> fieldMap = schemaMap.get(SobjectApiName).getDescribe().fields.getMap();

        String commaSepratedFields = '';
        for(String fieldName : fieldMap.keyset()){
            if(commaSepratedFields == null || commaSepratedFields == ''){
                commaSepratedFields = fieldName;
            }else{
                commaSepratedFields = commaSepratedFields + ', ' + fieldName;
            }
        }

        /////here i want to query with set of id's///

        query = 'select ' + commaSepratedFields + ' from ' + SobjectApiName +' where id='+'\'' + ids + '\'';
        system.debug('=====query===='+query);

       ////error occuring here as INVALID ID ('id','id', .... )////

        paList = Database.query(query);

Problem 1 :How to query the list of id's in dynamic query?

Problem 2 :I have a Look Up to Account object(Account is Master). When i query like above it is throwing as

"retrieved soql without querying the requested
field:Patient__c.Account__r".

How to Query the lookup relation in Dynamic query.

Thanks

Best Answer

Simple Just use set inside single quote

query = 'select ' + commaSepratedFields + ' , from ' + SobjectApiName +' where id IN: ids ';

Edit

Add Account__r.Name field in query

query = 'select Account__r.Name, ' + commaSepratedFields + ' , from ' + SobjectApiName +' where id IN: ids ';
Related Topic