Forum Discussion
IF with multiple statements in M language
Hi,
in Power Query, by a custom M code, is it possible to use IF with more statements for a satisfied condition? In another terms, is it possibile to have a block of instructions to run for an IF, delimited by a begin ... end construct or similar construct?
Many thanks
13 Replies
- ImkeFCommunity Champion
Hi Anonymous ,
you can compare the let-in-construct with a Begin-End-syntax like you've described.
Just have in mind that PQ is lazy, so it will only evaluate/execute steps that are necessary to evaluate the "in"-result.
So if every step shall be a single execution of something (which I'm having difficulties to imagine, but your question is fairly generic, so I'm not questioning that), then make sure that its result (or a reference to it) is referenced by the final result.
In the following valid M-code the "statement3" will not be executed, because it is not needed to evaluate the final result:if 1 = 1 // Condition then let // Begin Statement1 = 10, Statement2 = 20, Statement3 = 40 in Statement1 + Statement2 // End else 0If your statements shall do something more interesting like calling APIs for example, make sure that you reference their results somehow in what the "in" returns.
- Greg_DecklerCommunity Champion
Anonymous Not sure what you mean, like if then else if then else if then else or multiple logical criteria?
There is no switch or case statement in M
- v-kelly-msftCommunity Support
Hi Anonymous ,
You could use "if" with "else... then" for different senarios or use "if" with "and/or" with multiple conditions,check below reference:
https://gorilla.bi/power-query/if-function-in-power-query/
Best Regards,
KellyDid I answer your question? Mark my post as a solution!
- AnonymousNot applicable
As the great Ben Gribaudo put it, the only control structures in M are if/then/else. I your case, you probably want if/then/else/if. Basically, multiple conditions outcomes need to be chained together using else if, and conditions can use and/or logic:
if [Widget] = 4 and [Agent] = "Sam" then "Sam's Sale" else if [Widget] = 2 or [Agent].<> "Bob" then "Other" else "No one"
--Nate
- AnonymousNot applicable
I'm thinking to something like this:
if <condition>
<begin or other start construct>
<statement 1>
<statement 2>
...
<statement n>
<end or other end construct>
Thanks
- v-kelly-msftCommunity Support
Hi Anonymous ,
Could you pls make your requirement detailed?Such as providing some sample data with expected output?
Best Regards,
KellyDid I answer your question? Mark my post as a solution!
- mussaendaCommunity Champion
Hi Anonymous ,
Based on my understanding on your question, it is possible to do nested if else statements on Power Query.
Hope this helps.