Forum Discussion

jmdh's avatar
jmdh
Advocate IV
9 years ago
Solved

change column type programmatically

Can anyone help?   If i have a two col table TABLE1 (with columns Name and Type containing  the col name and its desired col type for an other table, TABLE 2   how can i handle that in advanced e...
  • MarcelBeug's avatar
    MarcelBeug
    9 years ago

    OK, that clarifies a bit: so the columns you specify in Table1 are columns that are included in Table2.

     

    Apart from the challenge to change your Table1 to a list with lists, another challenge is to convert text like "type number" from a text to an actual type.

     

    So, it's rather complicated, but the good news is that the following codes accomplishe the tasks. The "TextToType" step converts your textual types to actual types.

     

    Query ColumnSpecs in which the Source step represents your Table1:

     

    let
        Source = #table(type table[col name = text, col type = text],{   {"Sales", "type number"}, {"Profit", "type number"}  }),
        TextToType = Table.TransformColumns(Source,{{"col type", Expression.Evaluate}}),
        FieldValues = Table.AddColumn(TextToType, "Custom", each Record.FieldValues(_)),
        RemovedColumns = Table.RemoveColumns(FieldValues,{"col name", "col type"}),
        TableToList = RemovedColumns[Custom]
    in
        TableToList

     

    And Table2:

     

    let
        Source = #table({"Sales","Profit"},{{1000,300},{100,40}}),
        #"Changed Type" = Table.TransformColumnTypes(Source,ColumnSpecs)
    in
        #"Changed Type"