function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Michelle Chaplin RegalMichelle Chaplin Regal 

Error on dynamic SOQL query

I have a dynamic SOQL query that keeps causing an error with my test class. I'm sure it's formatted incorrectly, but I can't figure it out from the documentation. Can anyone help?
    public static date today = date.today();
    public static date tomorrow = today.addDays(1);
    public static date oneWeek = today.addDays(7);
    public static final Id eventRegistrationRecordTypeId = Schema.SObjectType.Opportunity.getRecordTypeInfosByName().get('Event Registration') == null ? null : Schema.SObjectType.Opportunity.getRecordTypeInfosByName().get('Event Registration').getRecordTypeId();
    public static final Id vipEventRecordTypeId = Schema.SObjectType.Campaign.getRecordTypeInfosByName().get('VIP Event') == null ? null : Schema.SObjectType.Campaign.getRecordTypeInfosByName().get('VIP Event').getRecordTypeId();
    private static string query = 'SELECT Id FROM Opportunity WHERE RecordTypeId = :eventRegistrationRecordTypeId AND Campaign.RecordTypeId = :vipEventRecordTypeId AND (StageName = "Closed Won" OR StageName = "Pledged") AND (Campaign.EndDate = :tomorrow OR Campaign.EndDate = :oneWeek)';

The error message I'm getting is System.QueryException: line 1:146 no viable alternative at character '"'
Raj VakatiRaj Vakati
Hi Michelle ,

Please use this once. Give proper spacing to while making the query .

string query = 'SELECT Id FROM Opportunity WHERE RecordTypeId ='+'\''+eventRegistrationRecordTypeId+'\''+
              'AND Campaign.RecordTypeId ='+'\''+vipEventRecordTypeId +'\'' +
                'AND (StageName = \'Closed Won\' OR StageName = \'Pledged\' )'+
        ' AND (Campaign.EndDate ='+ tomorrow +'OR Campaign.EndDate = '+oneWeek+')';
 
  
System.debug(query);

 
LBKLBK
Unless you have a use case for using a dynamic SOQL query, you can have a perfect static SOQL query that populates a List<Opportunity> object.
 
SELECT Id FROM Opportunity WHERE RecordTypeId = :eventRegistrationRecordTypeId AND Campaign.RecordTypeId = :vipEventRecordTypeId AND (StageName = 'Closed Won' OR StageName = 'Pledged') AND (Campaign.EndDate = :tomorrow OR Campaign.EndDate = :oneWeek)