SF :Salesforce中,動態拼接SOQL

Database.query(soql);


String strName = 'Test';

String soql = 'Select Id, Name From SObject';

if(Name != null){

    soql += 'And Name LIKE \'%' + strName.trim() + '%\'';

}


eg:

public void runQuery() {

        try {

            productList = Database.query(soql);

            //If there is empty,give a hint

            if(productList.isEmpty()){

                ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO, 'There is no such product in our ORG.'));

                return;

            }

           

        } catch (Exception e) {

            //Catch exceptions for abnormal hints

            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, e.getMessage()));

            return;

        }

    }

    

    public PageReference searchAction(){

       soql = 'Select ProductCode, Name, IsActive, Id, Family, Material_Cost__c, Description From Product2 Where Name != null';

       if (proName.trim() != null && !proName.trim().equals('')){

           soql += ' and Name LIKE \'%'+ String.escapeSingleQuotes(proName.trim()) + '%\'';

       }

       if (proCode.trim() != null && !proCode.trim().equals('')){

           soql += ' and ProductCode LIKE \'%' + String.escapeSingleQuotes(proCode.trim()) + '%\'';

       }

       runQuery();

       return null;

    }

**http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_dynamic_soql.htm

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章