Failed to cast argument 2 to scalar constant when using replace()

2.8k Views Asked by At

I'm trying to use replace when the 2nd argument to the function is a column field:

replace("bla", column1Field, orignalString)

But I'm getting the following error:

replace(): failed to cast argument 2 to scalar constant

Why am I getting this error and how to still use the column field with those functions?

1

There are 1 best solutions below

0
On BEST ANSWER

Update from Jul 2021:

The replace() function has been replaced with replace_regex() (just note that the order of the arguments changed). replace_regex() expects a regex lookup, and it must be a constant because Kusto "compiles" it, and it would be bad performance-wise to do it per record.

And there's a new replace_string() function that lets you do exactly what you want: replace one string with another (both can be non-const). So in your case, you should use replace_string(orignalString, "bla", column1Field)

Old answer:

The 2nd argument of replace() must be a constant because Kusto "compiles" it, and it would be bad performance-wise to do it per record.

An example (from the doc):

range x from 1 to 5 step 1
| extend str=strcat('Number is ', tostring(x))
| extend replaced=replace(@'is (\d+)', @'was: \1', str)

As you can see, the second parameter contains \1 which will take the value in str, that matches what's inside the ()s in the regex that's the first parameter.