Forum Discussion
Cleaning Text field columns from incoming SQL database
- 2 years ago
Hi RobRayborn,
Let's try something else...
Create a new blank query and replace everything inside with the following code:
let TrimAllTxtCols = (t as table, optional n as number) as table => Table.TransformColumns( t, List.Transform( List.Select( Table.ColumnNames(t), each if n = null then List.MatchesAll( Table.Column(t, _), (x) => Value.Is(x, type nullable text) ) else List.MatchesAll( List.FirstN(List.RemoveNulls(Table.Column(t, _)), n), (x) => Value.Is(x, type text) ) ), each {_, Text.Trim, type text} ) ) in TrimAllTxtColsThis returns a function value, you can give this query a more suitable name if you like.
Now for "t" pass it query with your incoming SQL data
When you have many rows in your table, I'd encourage you to also pass a number for "n" that tells the function how many rows to check, to see if your column contains text values.Hope that works for you.
Cheers.
Hi RobRayborn
Give something like this a go. If your columns aren't typed instead of Table.ColumnsOfType you can pass a list with all relevant column names. Note that you have to replace "Source" twice with the previous step name in your Query.
Table.TransformColumns( Source,
List.Transform(
Table.ColumnsOfType( Source, {type text}),
each {_, Text.Trim, type text}
)
)
To illustrate, you can copy this code into a new blank query.
let
TypedSource = Table.FromRows(
{
{" text", "text ", #date(2024,2,15)},
{" text", "text ", #date(2024,2,15)},
{" text", "text ", #date(2024,2,15)}
}, type table[ Col1=text, Col2=text, Col3=date]
),
ChType = Table.TransformColumns( TypedSource,
List.Transform(
Table.ColumnsOfType(TypedSource, {type text}),
each {_, Text.Trim, type text})
),
UntypedSource = Table.FromRows(
{
{" text", "text ", #date(2024,2,15)},
{" text", "text ", #date(2024,2,15)},
{" text", "text ", #date(2024,2,15)}
}
),
ChType2 = Table.TransformColumns( UntypedSource,
List.Transform(
List.FirstN( Table.ColumnNames(UntypedSource), 2),
each {_, Text.Trim, type text}
)
)
in
ChType2
I hope this is helpful