Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/postgresql/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/visual-studio-2012/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用sql变量更新PostgreSQL hstore字段_Sql_Postgresql_Hstore - Fatal编程技术网

使用sql变量更新PostgreSQL hstore字段

使用sql变量更新PostgreSQL hstore字段,sql,postgresql,hstore,Sql,Postgresql,Hstore,我有一个表文件,其中有hstore列详细信息。在sql语句中,我向其插入数据: UPDATE files SET details = 'new_users=>new_users_count'::hstore where id = v_file_id; 但我想用sql语句中可用的变量而不是字符串来更新这个hstore字段。我如何才能做到这一点?PL/pgSQL无法检测字符串文本中的变量。您需要使用hstore类型的“构造函数”方法来传递变量: UPDATE files SET

我有一个表
文件
,其中有hstore列
详细信息
。在sql语句中,我向其插入数据:

  UPDATE files SET details =  'new_users=>new_users_count'::hstore where id = v_file_id;

但我想用sql语句中可用的变量而不是字符串来更新这个hstore字段。我如何才能做到这一点?

PL/pgSQL无法检测字符串文本中的变量。您需要使用
hstore
类型的“构造函数”方法来传递变量:

UPDATE files 
   SET details = hstore('new_users', p_new_user_count)
where id = v_file_id;
如果
p\u new\u user\u count
定义为一个数字(而不是
varchar
text
),则需要将其转换为文本值:

UPDATE files 
   SET details = hstore('new_users', p_new_user_count::text)
where id = v_file_id;
更改问题后编辑

要对多个变量执行此操作,您可以连接两个hstore值:

details = hstore('new_users', p_new_user_count::text)||hstore('post_count', p_post_count::text)
或使用阵列:

details = hstore(array['new_users','post_count'], array[p_user_count, p_post_count]::text[]);

这些都记录在手册中:

如果您只需要更换hstore中的新用户,则

UPDATE files 
SET details = details || hstore('new_users', p_new_user_count::text)
where id = v_file_id;

它将替换列中已存在的新用户或添加新条目

我给出了以下错误:PG::UndefinedFunction:错误:函数hstore(未知,整数)不存在您的答案很好,但我还有一个问题。如何在这一个update语句中还添加另一个键?例如:posts_count=>posts_count_variable?@MateuszUrbański:查看我的编辑-但在收到答案后更改问题不是一个好做法。我希望避免创建下一个问题。非常感谢你的帮助。