在Power Query M函数中声明变量

时间:2018-06-27 08:51:56

标签: powerbi powerquery m

我正在尝试在Power Query中创建一个可重用的函数,该函数将由多个表使用。

这很好(写在空白查询中):

let
    is_emergency = (color as text) => 
    if color = "red" or color = "orange" then 
       "emergency" 
    else 
        "not emergency"  
in
    is_emergency

我可以使用类似=emergency([color_column])的自定义列来调用它。

但是-我的颜色列包含很多额外的空格,因此我需要以某种方式在颜色参数上调用Text.Trim()。怎么写?

我认为可以的就是写这个:

let
    is_emergency = (color as text) =>
    color = Text.Trim(color, " "),
    if color = "red" or color = "orange" then 
       "emergency" 
    else 
        "not emergency"  
in
    is_emergency

但这给了我错误Token Literal Expected

如何正确编写?我知道我可以使用Power Query GUI创建像这样的简单函数,但是我的实际情况更高级,我想了解M语法。

1 个答案:

答案 0 :(得分:1)

经过研究,我设法自己解决了。

let
    is_emergency = (color as text) =>
    // you need to put the variable declaration inside a new let - in
    let 
        trimmed_color = Text.Trim(color, " "), 
        // you also need to define the return value and return it in the new let - in
        return_value = if trimmed_color = "red" or trimmed_color = "orange" then 
            "emergency" 
        else 
            "not emergency"
    in
        return_value
in
    is_emergency