使用sql变量更新PostgreSQL hstore字段



我有表files,其中有hstore列details。在我的sql语句中,我插入数据到它:

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

,但我想更新这个hstore字段不与字符串,但与变量,可在我的sql语句。我该怎么做呢?

PL/pgSQL不能检测字符串文本中的变量。您需要使用hstore类型的"constructor"方法来传递一个变量:

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

如果您需要在hstore中只替换new_users,则

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

如果列中已经存在new_users,它将替换它,或者添加一个新条目。

最新更新