Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ncalm/2f872b42dbac0301d2fb138a684085c5 to your computer and use it in GitHub Desktop.
Save ncalm/2f872b42dbac0301d2fb138a684085c5 to your computer and use it in GitHub Desktop.
This M pattern shows how we can build a dynamic list of column names and column types then change the column types using the list. In this way, we can avoid hard-coding into the query the column names whose types we want to change
/*
Intent here is to transform many columns at once without hard-coding the column names into the query (in case the column names change in an update to the source)
Longer with comments to explain (shorter embedded version below)"
*/
let
Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
//start by getting all the column names
all_cols = Table.ColumnNames(Source),
//and a list of columns we don't want to change
no_change = {"item"},
//remove the no_change list from the cols list
change_cols = List.RemoveItems(all_cols,no_change),
//create a list the same length as change_cols, containing the type we want to change to
type_list = List.Repeat({Int64.Type},List.Count(change_cols)),
//build the transforms list by zipping the change_cols with the type_list
trf = List.Zip({change_cols,type_list}),
//finally, change the types by using the transformed list of columns
//each item in trf is {"column_name",column_type}
//e.g. {"4721",Int64.Type}
change_types = Table.TransformColumnTypes(Source,trf)
in
change_types
/*
Intent here is to transform many columns at once without hard-coding the column names into the query (in case the column names change in an update to the source)
Shorter version in single step:
*/
let
Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
change_types = Table.TransformColumnTypes(
Source,
List.Zip(
{
List.RemoveItems(Table.ColumnNames(Source),{"item"}),
List.Repeat(
{Int64.Type},
List.Count(
List.RemoveItems(Table.ColumnNames(Source),{"item"})
)
)
}
)
)
in
change_types
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment