Switch statement in Apex SOQL - salesforce

I have below SOQL statement in an Apex class, Column Promotion returns true or false, If the value is true then it should return 'Promo Enabled' otherwise ''. Can we handle this within the select query?
#AuraEnabled
public static Object searchLocations(Decimal lon, Decimal lat, Integer radius, Integer resultSize){
return Database.query('SELECT Id, Name, Street, City, State, PostalCode, Country, Primary_Phone_Number__c, Promotion,'+
'DISTANCE(Address, GEOLOCATION('+lat+', '+lon+'), \'mi\') '+
'FROM ServiceTerritory WHERE DISTANCE(Address, GEOLOCATION('+lat+', '+lon+'), \'mi\')>0 '+
'AND DISTANCE(Address, GEOLOCATION('+lat+', '+lon+'), \'mi\')<'+radius+
' AND IsActive=TRUE '+
'ORDER BY DISTANCE(Address, GEOLOCATION('+lat+', '+lon+'), \'mi\') LIMIT '+resultSize);
}

SOQL has only handful of functions and no arithmetic for example, you can't add 2 fields together or compare field to field (only field to value)
Some are here:
https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/sforce_api_calls_soql_select_agg_functions.htm
https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/sforce_api_calls_soql_select_date_functions.htm
https://salesforce.stackexchange.com/questions/166372/all-functions-available-in-soql
You'd need to create a custom formula (text) field and include it in the query (it'll be calculated in runtime, they act a bit like views in normal SQL).
Alternatively return some custom data structure (List<Wrapper> where each entry is a helper class consisting of ServiceTerritory and Boolean) or do the calculation client-side.

Related

"Invalid field for upsert, must be an External Id custom or standard indexed field: Name" error

I am trying to enter unique values to the Contact object. Here is the code:
List<Contact> conList = new List<Contact> {
new Contact(FirstName='Joe',LastName='Smith',Department='Finance'),
new Contact(FirstName='Kathy',LastName='Smith',Department='Technology'),
new Contact(FirstName='Caroline',LastName='Roth',Department='Finance'),
new Contact()};
// Caroline Roth already exists so I want this code to update her record, not insert another Caroline Roth record
Database.UpsertResult[] srList = Database.upsert(conList, Contact.Fields.Name, false);
Salesforce's documentation states
"The upsert statement matches the sObjects with existing records by comparing values of one field. If you don’t specify a field when calling this statement, the upsert statement uses the sObject’s ID to match the sObject with existing records in Salesforce. Alternatively, you can specify a field to use for matching. For custom objects, specify a custom field marked as external ID. For standard objects, you can specify any field that has the idLookup property set to true. For example, the Email field of Contact or User has the idLookup property set."
I have two questions:
1) how can we see which fields on the Contact object have their idLookup property set to true
2) why am I getting the error in the subject line when I execute the code?
1:
Map<String, Schema.SObjectField> contacFieldsMap = Schema.getGlobalDescribe().get('Contact').getDescribe().fields.getMap();
for (Schema.SObjectField field : contacFieldsMap.values()) {
Schema.DescribeFieldResult fieldResult = field.getDescribe();
if (fieldResult.isIdLookup()) System.debug(fieldResult.getName() + ' IS idLookup');
}
2: System.debug(Contact.Name.getDescribe().isIdLookup()); // false

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

SQL XML parsing using a attribute value supplied by another field in the same row

Context: I'm scraping some XML form descriptions from a Web Services table in hopes of using that name to identify what the user has inputted as response. Since this description changes for each step (row) of the process and each product I want something that can evaluate dynamically.
What I tried: The following was quite useful but it returns a dynamic attribute query result in it's own field ans using a coalesce to reduce the results as one field would lead to it's own complications: Get values from XML tags with dynamically specified data fields
Current Attempt:
I'm using the following code to generate the attribute name that I will use in the next step to query the attribute's value:
case when left([Return], 5) = '<?xml'
then lower(cast([Return] as xml).value('(/response/form/*/#name)[1]','varchar(30)'))
else ''
end as [FormRequest]
And as part of step 2 I have used the STUFF function to try and make the row-level query possible
case when len(FormRequest)>0
then stuff( ',' + 'cast([tmpFormResponse] as xml).value(''(/wrapper/#' + [FormRequest] + ')[1]'',''varchar(max)'')', 1, 1, '')
else ''
end as [FormResponse]
Instead of seeing 1 returned as my FormReponse feild value for the submit attribute (please see in yellow below) it's returning the query text -- cast([tmpFormResponse] as xml).value('(/wrapper/#submit)1','varchar(max)') -- instead (that which should be queried).
How should I action the value method so that I can dynamically strip out the response per row of XML data in tmpFormResponse based on the field value in the FormRequest field?
Thanx
You can check this out:
DECLARE #xml XML=
N'<root>
<SomeAttributes a="a" b="b" c="c"/>
<SomeAttributes a="aa" b="bb" c="cc"/>
</root>';
DECLARE #localName NVARCHAR(100)='b';
SELECT sa.value(N'(./#*[local-name()=sql:variable("#localName")])[1]','nvarchar(max)')
FROM #xml.nodes(N'/root/SomeAttributes') AS A(sa)
Ended up hacking up a solution to the problem by using PATINDEX and CHARINDEX to look for the value in the [FormRequest] field in the he tmpFormResponse field.

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 print the array element of a form in another form in vb6.0

I want to store the records for different newspapers with descriptions (like name,price,date of publishing) and want to show them in another form whenever it is loaded. What is the simplest method to do this process without using database.
You can use a UDT (User Defined Type) structure:
in MODULE BAS
Public Type TYPE_Newspapers ' Create your type structure
' Define items
Name As String * 100
Price As Currency
PublishDate As Date
End Type
in Form:
Public MyNewspapers(1 to 100) As TYPE_Newspapers
With MyNewspapers(1)
.Name = "Wall Street Journal"
.Price = 1
.PublishDate = #01/01/2017#
End With
and so on...

Resources