1

Using the below code, I get this error message:

An unexpected error occurred. Please include this ErrorId if you contact support: 76743200-1017657 (1358022652)

String sql = 'SELECT Id, DeveloperName FROM RecordType WHERE SObjectType =Case';
Map<Id,RecordType> caseMap = new Map<Id, RecordType>([sql]);

I am from Java background I know below works fine, but why not above ?

Map<Id,RecordType> caseMap = new Map<Id, RecordType>([SELECT Id, DeveloperName FROM RecordType WHERE SObjectType = 'Case']);

2 Answers 2

3

You need to wrap any string literal in quotes. When using a dynamic query, you must also escape them.

'... WHERE SObjectType = \'Case\''
// missing:              ^^    ^^

Or you could also rewrite that as:

String caseType = '\'Case\'';
// wrap in quotes!    ^^    ^^

String soql = 'SELECT DeveloperName FROM RecordType WHERE SObectType = ' + caseType;

Or better yet, use merge variables:

String sObjectType = 'Case';
String soql = 'SELECT DeveloperName FROM RecordType WHERE SObjectType = :caseType';

As written, your current query would be the same as:

SELECT DeveloperName FROM RecordType WHERE SObjectType = Case

This query is obviously invalid. As stated above, the filter value needs to be wrapped in single quotes (as you do in the static version you include in the question).


A couple asides:

  1. The query language is named SOQL, not SQL.
  2. You should always favor static queries over dynamic when they are viable.
  3. When merging in strings provided by a user, make sure you escape single quotes to avoid injection vulnerabilities.
2
  • I tried that this also doesn't works. It says unexpected sql. String str = 'Case'; String sql = 'SELECT Id, DeveloperName FROM RecordType WHERE SObjectType='+str; Map<Id,RecordType> caseRTMap = new Map<Id, RecordType>([sql]);
    – user46657
    Commented Jul 25, 2017 at 19:07
  • @MattW You didn't try what I recommended, what you did is completely different and just replicates the error...
    – Adrian Larson
    Commented Jul 25, 2017 at 19:09
1

You need to use the appropriate method if you choose to use a string for your SOQL. The following (almost) works:

String sql = 'SELECT Id, DeveloperName FROM RecordType WHERE SObjectType =Case';
Map<Id,RecordType> caseMap = new Map<Id, RecordType>(Database.query(sql));

As pointed out by Adrian, you need to use quotes when a String is expected:

String sql = 'SELECT Id, DeveloperName FROM RecordType WHERE SObjectType =\'Case\'';

The [query] notation only works for literal queries:

Map<Id,RecordType> caseMap = new Map<Id, RecordType>([
    SELECT DeveloperName FROM RecordType WHERE SObjectType = 'Case'
]);

You must log in to answer this question.