使用SQL变量更新PostgreSQL hstore字段

7

我有一个名为files的表,这个表里有一个hstore类型的列details。在我的sql语句中,我向它插入数据:

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

但我想更新这个hstore字段,不是用字符串,而是用在我的SQL语句中可用的变量。我该怎么做?


我收到了以下错误:PG::UndefinedFunction: 错误:函数hstore(unknown,integer)不存在 - Mateusz Urbański
2个回答

14

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

UPDATE files 
   SET details = hstore('new_users', p_new_user_count)
where id = v_file_id;
如果p_new_user_count被定义为数字(而不是varchartext),则需要将其转换为文本值:
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[]);

这些都在手册中有详细记录:http://www.postgresql.org/docs/current/static/hstore.html


你的回答很棒,但我还有一个问题。怎么在这个更新语句中同时添加另一个键呢?比如:posts_count => posts_count_variable? - Mateusz Urbański
1
@MateuszUrbański:看看我的编辑-但在收到答案后更改问题并不是一个好的做法。 - user330315
我想避免创建下一个问题。非常感谢您的帮助。 - Mateusz Urbański

5

如果您只需要在hstore中替换new_users,则执行以下操作:

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

如果该列中已经存在new_users,则它将替换掉该现有值;否则,它将添加一个新条目。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接