Kdb q - update statement in try catch

In q, let's say someone was naughty and created a function that sometimes returns a table with a mixed-type column:

t:([] c1:(`a;"dfdf";`b;"ccvcv")) 

and sometimes a table with a column for characters only:

 t:([] c1:`a`dfdf`b`ccvcv) 

I want to update c1 to contain only characters in try-catch if t c1` already contains only characters. But it's hard for me to translate the statement

 update c1:`$c1 from t where 10h=type each c1 

into the syntax ![t;c;b;a] , which works with the try-catch @ operator

 t:([] c1:(`a;"dfdf";`b;"ccvcv")); c:enlist(=;type each `c1;10h); b:0b; a:(enlist`c1)!(enlist `$`c1); / TYPE ERROR @[![;c;b;a];t;`continue] / this is what I want to do 

thanks for the help

+5
source share
2 answers

Your a should be defined as follows:

 a:(enlist`c1)!enlist($;enlist`;`c1) 

You can get this using parse in your original Q-SQL update expression:

 q)parse "update c1:`$c1 from t where 10h=type each c1" ! `t ,,(=;10h;(k){x'y};@:;`c1)) 0b (,`c1)!,($;,`;`c1) 

Noting that , in k there is an enlist in Q

You also need to change the definition of c :

 c:enlist(=;(each;type;`c1);10h); 

Putting it all together:

 q)t:([] c1:(`a;"dfdf";`b;"ccvcv")) q)c:enlist(=;(each;type;`c1);10h); q)b:0b; q)a:(enlist`c1)!enlist($;enlist`;`c1) q)![t;c;b;a] c1 ----- a dfdf b ccvcv 

But, as pointed out in another answer, it is best to avoid a functional form where possible.

+5
source

Sometimes it is better to avoid functional selections, if your use case allows, then @ modify is a great alternative that can be especially useful instead of update statements.

 q)@[t;`c1;{$[10=type x;`$x;x]}each] c1 ----- a dfdf b ccvcv 

Or if you still want to use try-catch:

 q)@[t;`c1;{@[`$;x;x]}each] c1 ----- a dfdf b ccvcv 
+2
source

Source: https://habr.com/ru/post/1276018/


All Articles