Cannot extract year from createdDate in SOQL query - salesforce

SELECT House__r.Name, House__r.House_Owner__r.person__r.Email__c, (SELECT Name, Total_Balance__c, Total_Expense__c FROM Expenses__r Where Type__c='Yearly' AND AND CALENDAR_YEAR(CreatedDate) = CALENDAR_YEAR(System.today() ) FROM Member__c
Error=> Unknown parsing error.
Kindly suggest what else can I do.

You have two 'AND' in a row. Also, if you are using query editor, you can't use System.today().

(on mobile, formatting will be poor, sorry)
SOQL supports only "field - operator - value_or_function” style for conditions. You try to make it "function - operator - another function", won't work.
For your particular scenario try with WHERE Created date = THIS_YEAR. It's a special literal, see https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/sforce_api_calls_soql_select_dateformats.htm
More generic way would be to write what you need as a formula field, you could compare to YEAR(TODAY()). (that could be poor performance to filter by formula, often it results in full table scan, you would have to test, maybe add more filters using indexed columns...).
Or write it as WHERE CreatedDate >= :start AND CreatedDate <= :stop, put right bind variables for your range.

Related

How to match a substring exactly in a string in SQL server?

I have a column workId in my table which has values like :
W1/2009/12345, G2/2018/2345
Now a user want to get this particular id G2/2018/2345. I am using like operator in my query as below:
select * from u_table as s where s.workId like '%2345%' .
It is giving me both above mentioned workids. I tried following query:
select * from u_table as s where s.workId like '%2345%' and s.workId not like '_2345'
This query also giving me same result.
If anyone please provide me with the correct query. Thanks!
Why not use the existing delimiters to match with your criteria?
select *
from u_table
where concat('/', workId, '/') like concat('%/', '2345', '/%');
Ideally of course your 3 separate values would be 3 separate columns; delimiting multiple values in a single column goes against first-normal form and prevents the optimizer from performing an efficient index seek, forcing a scan of all rows every time, hurting performance and concurrency.

SOQL Query - How to write a SOQL query by making a field to lowercase and compare?

Following query returns an error:
Query:
SELECT Id, FirstName, LastName, OwnerId, PersonEmail
FROM Account
WHERE lower(PersonEmail) = lower('abc.DEF#org.cOM')
API Response:
success: false
result: Dictionary
error: IntegrationError
title: "The JSON body contains an error"
message: "Salesforce returned the following error code: MALFORMED_QUERY"
detail: "
'%test%' and lower(PersonEmail) = lower('abc.DEF#org.cOM')
^
ERROR at Row:4:Column:54
Bind variables only allowed in Apex code"
Can't we use SQL functions in SOQL?
You do not need to change the text to lower case:
Comparisons on strings are case-sensitive for unique case-sensitive fields and case-insensitive for all other fields
EDIT: to put it another way, only specific fields are uniquely marked to be case sensitive. The rest aren't. Also, emails are stored as all lowercase by default. Also, try the LIKE comparison, which (I believe) is case insensitive even for case sensitive fields.
Can't we use SQL functions in SOQL?
No, you can't. SOQL is a Salesforce-specific dialect. Here's a decent list of what you can use: https://salesforce.stackexchange.com/questions/166372/all-functions-available-in-soql. And any comparison you make must be in field operator value style. You can't compare field value with another field's value (apart from primary / foreign keys... you could write formulas for that though). And you can't do "clever" weird queries WHERE 1=1 AND...
This is not too different from other SQL dialects really? To me SQL Server's date format "112" is equally strange as to you lack of LOWER. If you really want to have a lowercase value returned/displayed in UI you can make a formula field in SF (bit like adding a column to materialized view?) - but comparisons on it will still be case-insensitive and probably slower, full table search to run ultimately useless function instead of using indexes.
SOQL is case insensitive on database level (I believe it's called collation?). Any SELECTs you make will return hits ignoring case so you don't have to explicitly call LOWER() There are some exceptions to this but PersonEmail is not one of them:
If you have custom field marked as unique case sensitive (you could ask admin to build an automationt hat copies value from PersonEmail to such custom field but i don't think there's a point)
If you use Platform Encryption (a.k.a. Salesforce Shield) and used Deterministic Encryption method with case-sensitive option.

How to take apart information between hyphens in SQL Server

How would I take apart a column that contains string:
92873-987dsfkj80-2002-04-11
20392-208kj48384-2008-01-04
Data would look like this:
Filename Yes/No Key
Abidabo Yes 92873-987dsfkj80-2002-04-11
Bibiboo No 20392-208kj48384-2008-01-04
Want it to look like this:
Filename Yes/No Key
Abidabo Yes 92873-987dsfkj80-20020411
Bibiboo No 20392-208kj48384-20080104
whereby I would like to concat the dates in the end as 20020411 and 20080104. From the right side, the information is the same always. From the left it is not, otherwise I could have concatenated it. It is not an import issue.
As mentioned in the comments already, storing data like this is a bad idea. However, you can obtain the dates from those strings by using a RIGHT function like so:
SELECT RIGHT('20392-208kj48384-2008-01-04', 10)
Output:
2008-01-04
Depending on the SQLSERVER version you are using, you can use STRING_SPLIT which requieres COMPATIBILITY_LEVEL 130. You can also build your own User Defined Function to split the contents of a field and manipulate it as you need, you can find some useful examples of SPLIT functions in this thread:
Split function equivalent in T-SQL?
Assuming I'm correct and the date part is always on the right side of the string, you can simply use RIGHT and CAST to get the date (assuming, again, that the date is represented as yyyy-mm-dd):
SELECT CAST(RIGHT(YourColumn, 10) As Date)
FROM YourTable
However, Panagiotis is correct in his comment - You shouldn't store data like that. Each column in the database should hold only a single point of data, be it string, number or date.
Update following your comment and the updated question:
SELECT LEFT(YourColumn, LEN(YourColumn) - 10) + REPLACE(RIGHT(YourColumn, 10), '-', '')
FROM YourTable
will return the desired results.

MS SQL Excel Query wildcards

I'm trying to introduce LIKE clause with wildcards in SQL query that runs within Excel 2007, where parameters are taken from specific Excel cells:
SELECT Elen_SalesData_View.ItemCode, Elen_SalesData_View.ItemDescription,
Elen_SalesData_View.ItemValue, Elen_SalesData_View.Quantity,
Elen_SalesData_View.CustomerId, Elen_SalesData_View.CustomerName,
Elen_SalesData_View.SalesInvoiceId, Elen_SalesData_View.EffectiveDate,
Elen_SalesData_View.CountryId
FROM SM_Live.dbo.Elen_SalesData_View Elen_SalesData_View
WHERE (Elen_SalesData_View.EffectiveDate>=? And Elen_SalesData_View.EffectiveDate<=?)
AND (Elen_SalesData_View.CustomerName<>'PROMO')
AND (Elen_SalesData_View.ItemDescription LIKE '%'+?+'%')
The EffectiveDate parameters are running fine and bringing back data as expected. But since I introduced LIKE - query runs, but returns nothing.
It doesn't return any results without wildcards either (full description entered):
(Elen_SalesData_View.ItemDescription LIKE ?)
Is there a restriction to wildcards or LIKE clause? If so, is there a way around it? (I cannot use CONTAINS, as the ItemDescription field is not FULLTEXT)
Have a look at this reference which suggests that % itself is the wildcard character, although it may depend on the dialect of SQL you are using. If this is the case then your LIKE clause will simply be LIKE '%' but untested.
I've just got this to work by using the (Elen_SalesData_View.ItemDescription LIKE ?) syntax then having the cell that contains the parameter value include the wildcard characters. If you don't/can't include the wildcards then create a formula in a separate cell to wrap the value in % characters and use this cell for the parameter value.
Rhys
My query was correct. There was something wrong with the actual spreadsheet. After redoing all from scratch - it worked!
SELECT Elen_SalesData_View.ItemCode, Elen_SalesData_View.ItemDescription,
Elen_SalesData_View.ItemValue, Elen_SalesData_View.Quantity,
Elen_SalesData_View.CustomerId, Elen_SalesData_View.CustomerName,
Elen_SalesData_View.SalesInvoiceId, Elen_SalesData_View.EffectiveDate,
Elen_SalesData_View.CountryId
FROM SM_Live.dbo.Elen_SalesData_View Elen_SalesData_View
WHERE (Elen_SalesData_View.ItemDescription Like '%'+?+'%')
AND (Elen_SalesData_View.EffectiveDate>=?) AND (Elen_SalesData_View.EffectiveDate<=?)
AND (Elen_SalesData_View.CustomerName<>'PROMO')

Using calculated member as parameter in MDX function

I'm new to MDX but want to keep my code as clean as possible.
I have a query that looks at todays sales and compares them against LY and LY-1 using the ParallelPeriod function. It looks something like this..
With Member [Date].[SalesCalendar].[DateToday] as [Date].[SalesCalendar].[Date].&[2012-10-26T00:00:00]
SELECT
{[Date].[SalesCalendar].[DateToday],
ParallelPeriod([Date].[SalesCalendar].[Year],1,[Date].[SalesCalendar].[Date].&[2012-10-26T00:00:00]),
ParallelPeriod([Date].[SalesCalendar].[Year],2,[Date].[SalesCalendar].[DateToday]}
*
{[Measures].[Total Sales],[Measures].[Units],[Measures].[Sales Target]}
ON Columns,
[Locations].[Location PK].[Location PK]
on Rows
From MyCube
I start by defining a member that points to today's date. I want to define it once and use it throughout this query (and other queries I write), the theory being I can change it in once place and the underlying query reacts.
The problem I have is that if I try and use this calculated member within the ParallelPeriod function I get no results. With the query above I get results for the first column and the first call to ParallelPeriod (for LY) works but the second call for LY-1, which uses the declared member, fails.
I'm guessing this is down to my lack of knowledge with MDX and so I guess I am missing something fundamental. However, banging my head against the wall isn't working so I need some help!
Any ideas what I am doing wrong?
Thanks
This cannot work because when your query is evaluated [Date].[SalesCalendar].[DateToday] is not replaced with [Date].[SalesCalendar].[Date].&[2012-10-26T00:00:00].
You created a member that will give the same numeric values than [Date].[SalesCalendar].[Date].&[2012-10-26T00:00:00] in the pivot table cells.
You can try this query:
With Member [Date].[SalesCalendar].[DateToday] as [Date].[SalesCalendar].[Date].&[2012-10-26T00:00:00]
Member [Measures].[name] as [Date].[SalesCalendar].CurrentMember.Name
SELECT
{[Measures].[name], [Measures].[Total Sales]} ON Columns,
{[Date].[SalesCalendar].[DateToday], [Date].[SalesCalendar].[Date].&[2012-10-26T00:00:00]} on Rows
From MyCube
The Total Sales will be the same but not [Measures].[name].

Resources