Forum Discussion

Anonymous's avatar
Anonymous
Not applicable
4 years ago
Solved

Dynamically Change Column Type based on Column Name/Type from another table

Hi All   I have project where I need to dynamically Rename Columns and change the Column Types based on a Master List.   This is my current Master List which includes: TABLE_NAME = Original Sour...
  • ImkeF's avatar
    ImkeF
    4 years ago

    Hi KNP   ,
    funny, my understanding of Anonymous s request is just about a topic that I intended to blog about for some time (but too busy currently). Done that in some customer projects as well lately and it works really good. I find it especially useful when working with dataflows.
    But I'm attaching the file here.
    The transformations are done using this function:

    (TableToBeTransformed as table, TableName as text) =>
        let
            FilterMatchingTableFromMapping = Table.SelectRows(ColumnMapping, each [Table] = TableName),
            TablesColumnNames = Table.FromColumns({Table.ColumnNames(TableToBeTransformed)}),
            FilterRelevantColumns = Table.NestedJoin(
                FilterMatchingTableFromMapping,
                {"old"},
                TablesColumnNames,
                {"Column1"},
                "TablesColumnNames",
                JoinKind.Inner
            ),
            RenameColumns = Table.RenameColumns(
                TableToBeTransformed,
                List.Transform(Table.ToRecords(FilterRelevantColumns), each {_[old], _[new]})
            ),
            #"Changed Type" = Table.TransformColumnTypes(
                RenameColumns,
                List.Transform(
                    Table.ToRecords(FilterRelevantColumns),
                    each {_[new], fnReplaceTypes(_[Type])}
                )
            )
        in
            #"Changed Type"

     

    Hope this is what you've been looking for.