Getting query results in Workbench , Not in apex class/Script - salesforce

Background: I need access account records in the apex class where name contains %
For example, the query should return below accounts
abcd10%
cdcd40%abcd
10%volume
When I execute the below query I am getting results in the workbench
select id, name from Account where Name LIKE '%\%%'
the same query If I execute in Anonymous window/apex execute getting no results.
List accList = [select id,name from Account where Name LIKE '%\%%'];
system.debug('accList :::'+accList.size());
If we observe the below image, it is appending extra / in the query and giving wrong results.
Can you please help me how to resolve this?
16:00:21:002 SOQL_EXECUTE_BEGIN [1]|Aggregations:0|SELECT id, name FROM Account WHERE Name LIKE '%\%%'

You could use a bind variable or dynamic SOQL.
String searchText = '%\\%%';
List<Account> accs = [SELECT Id, Name
FROM Account
WHERE Name LIKE :searchText];
System.debug(accs.size());
System.debug(accs);
// Or in dynamic query (looks bit crazier because ' has to be escaped too)
List<Account> accs2 = Database.query('SELECT Id, Name FROM Account WHERE Name LIKE \'%\\%%\'');
System.debug(accs2);

Related

Can i create a sql table populated with Salesforce objects?

does Salesforce offer a way to obtain all Objects like Account, Contact etc and populate them in a SQL table with certain columns like
ObjectEntity, FieldName , FieldType ?
I'm pretty sure the only way to achieve this would be by using the Schema.sObjectType and Schema.sObjectField. Here is a link to the documentation for getting all sObjects. You will basically call the Schema.getGlobalDescribe() method which will return you a map of sObjectTypes with their sObject name as the key. Then you'll need to call getDesribe() on each sObjectType get the fields of the object from that Describe result. You'll again need to call getDescribe() on each sObjectField in order to have access to the columns you wanted (eg. FieldType). Here is the documentation on that You could save each DescribeFieldResult into a list that goes into a Map of > with the sObject name as the key, then you could do what you want with them... Put them in a table if you like. Keep in mind this is all going to be very expensive when it comes to CPU time. You may even run into some governor limits.
Here is a little example you can run using Execute Anonymous in the developer console where the sObject Name and all its field names and types are printed to the debug logs
Map<String, sObjectType> objects = Schema.getGlobalDescribe();
for(String objName : objects.keySet()){
system.debug('=======' + objName + '=========\n Fields: ');
sObjectType o = objects.get(objName);
DescribeSobjectResult oDRes = o.getDescribe();
Map<String, Schema.SObjectField> fields = dResult.fields.getMap();
for(Schema.SObjectField f : fields.values()){
DescribeFieldResult fDRes = f.getDescribe();
system.debug('name: ' + fDRes.getName() + ' | type: ' + fDRes.getType());
}
}
Hope this helps

Apex SOQL query removing object type designation from id in query

I am attempting to query a custom object that has a master detail lookup relation with opportunities. When I build the query dynamically I am getting an SOQL error:
System.QueryException: unexpected token: 'A000000VmhPyIAJ'
The first three characters of the ID have been dropped in that exception, the full ID is:
006A000000VmhPyIAJ
If I dump the query string with System.debug I get this (with the full ID):
SELECT id, isdeleted, name, createddate, createdbyid, lastmodifieddate, lastmodifiedbyid, systemmodstamp, lastactivitydate, opportunity__c, issue__c, description__c, ... FROM Exceptions__c WHERE Opportunity__c = 006A000000VmhPyIAJ
If I pass this exact same string into the database.query() I get results as expected.
Anyone have any idea what is causing this? The code that is generating that query is a library that I use for hundreds of other queries through out our custom Apex, and none of those queries are failing.
The actual query block:
try {
String query = 'SELECT id, isdeleted, name, createddate, createdbyid, lastmodifieddate, lastmodifiedbyid, systemmodstamp, lastactivitydate, opportunity__c, issue__c, description__c, ... FROM Exceptions__c WHERE Opportunity__c = 006A000000VmhPyIAJ';
exceptions = database.query( query );
} catch(DmlException e) {
System.debug('DmlException: ' + e);
}
Forgot to escape single quotes on the where clause value.
WHERE Opportunity__c = '006A000000VmhPyIAJ'

How to put result of soql query in map<Id,String>

I have created a trigger in Salesforce and i am fetching the result by soql query and store the result in a map, but it show the following error:
Error: Compile Error: Invalid initializer type List found for
Map: expected a Map with the same key and value types, or a
valid SObject List at line 7 column 25
trigger insertUpdateOwnerToSalesRep on Account (after insert, before update) {
if (trigger.IsAfter && trigger.IsUpdate) {
List<User> lstUser =[select id,name from User where Id in:(Trigger.NewMap).keySet()];
//Map<Id,String> ac=new Map<Id,String>([]);
Map<ID, String> m = new Map<ID, String>([select id,name from User where Id in:(Trigger.NewMap).keySet()]);
for(Account ac:Trigger.New) {
System.debug('^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\t'+ac.ownerid);
if (ac.owner!=null) {
User user=ac.owner;
System.debug('!!!!!!!!!!!!!!\t'+user);
//ac.Sales_Rep__c=ac.owner.userName;
}
}
}
}
Please help, Thanks in advance.
First, You try to select users by Id, but when you call Trigger.NewMap.keySet(), you will get set of account Ids, not user (because trigger on account object). Possibly, you want to get all users related to account, so use AccountId in 'where' condition. Also I'd like to note, that you don't use 'lstUser' variable after getting.
As for getting Map from select, you should use Map<Id, User> instead of Map<Id, String>:
Map<Id, User> m = new Map<Id, User>([SELECT Id, Name FROM User where AccountId in :(Trigger.NewMap).keySet()]);

Can't select User ID from Salesforce

I'm trying to select user's subordinates from Salesforce, but a simple query
SELECT Id FROM User WHERE ManagerId=xxxxxxxxx
returns bunch of null values, when I run
SELECT Id,Name FROM User WHERE ManagerId=xxxxxxxx
I get the correct names, still no IDs.
Is this a permission issue? I can't find anything when I login to portal.
I'm running the queries via API on Sandbox environment.
Try this (both works for me allways):
Id myId = [Select Id From User Where Username = 'myUserName'].Id;
System.debug('#### myId: ' + myId);
List<User> myIdList = [Select Id From User Where Username = 'myUserName' Limit 1];
System.debug('#### myId from list: ' + myIdList[0].Id);
Portal Licence doesn't allow to query User. However you have still access to the name of the user through OwnerId, CreatedById, LastModifiedById using in an inputfield.
i.e :
If you want to have access to user through the portal you need a custom object and synchronise your records with User by trigger.

I use the SELECT query to download contacts from Salesforce.com. As it is given below and i am getting "MALFORMED_QUERY" exception

I use this select query and i am not getting what's the wrong with this.
Select Id,Contact.FirstName,Contact.LastName,Contact.Title,Contact.Department,Contact.Birthdate,
Contact.Phone,Contact.HomePhone,Contact.MobilePhone,Contact.OtherPhone,Contact.Fax,Contact.Email,Contact.MailingStreet,
Contact.MailingCity,Contact.MailingState,Contact.MailingCountry,Contact.MailingPostalCode,Contact.OtherStreet,
Contact.OtherCity,Contact.OtherState,Contact.OtherCountry,Contact.OtherPostalCode,Contact.Description,Contact.Account.Name From Contact where strcmp('%#',Id) = -1",lastcontactId
You need to generate a query that uses =, e.g.
select name from contact where id='005123123123123123'
so, you can use this to generate the query.
NSString *query = [NSString stringWithFormat:#"select name,etc from contact where id='%#'", lastContactId];
Here's the SOQL docs which has more examples.
And if you're trying to do paging, you should just run the entire query and use query/queryMore to page through the results.

Resources