SF :Salesforce中,动态拼接SOQL

本文介绍了如何在Salesforce中使用SOQL进行动态查询。通过条件判断,动态地添加搜索条件到SOQL语句中,实现对产品名称和产品代码的模糊匹配查询。此外,还包含了异常处理和查询结果为空时的提示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值