[英]How to search for a particular key in a key value pair and return the corresponding value of it using sql function
Suppose the function is taking two inputs 4 and '3:66,8:54,4:23' , the function should search for 4 in the key value pair '3:66,8:54,4:23' , if key 4 is found then it should return corresponding value of it i,e:23 else it should return empty. 假设函数接受两个输入4和'3:66,8:54,4:23',则函数应在键值对'3:66,8:54,4:23'中搜索4,如果输入key找到4,则应返回其对应的值,即e:23,否则应返回为空。 How to write the function for it in sql.
如何在sql中为其编写函数。
You didn't tell us the database product you are using. 您没有告诉我们您正在使用的数据库产品。
In Postgres you can do that using string_to_array()
combined with split_part()
: 在Postgres中,您可以使用
string_to_array()
与split_part()
结合使用:
select split_part(x.kv, ':', 2)
from unnest(string_to_array('3:66,8:54,4:23', ',')) as x(kv)
where split_part(x.kv, ':', 1) = '4';
You can put that into a SQL function: 您可以将其放入SQL函数中:
create function get_key_value(p_input text, p_key text)
returns text
as
$$
select split_part(x.kv, ':', 2)
from unnest(string_to_array(p_input, ',')) as x(kv)
where split_part(x.kv, ':', 1) = p_key;
$$
language sql;
Then use: 然后使用:
select get_key_value(''3:66,8:54,4:23'', '4');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.