I have table files
which has hstore column details
. In my sql statement I insert data to it:
UPDATE files SET details = 'new_users=>new_users_count'::hstore where id = v_file_id;
but I want to update this hstore field not with string but with variable that is available in my sql statement. How can I do this?
Querying data from an hstore column is similar to querying data from a column with native data type using the SELECT statement as follows: Postgresql hstore provides the -> operator to query the value of a specific key from an hstore column.
Use the PostgreSQL UPDATE statement to update data in one or more columns of a table. Use the RETURNING clause to return the updated rows from the UPDATE statement Was this tutorial helpful ? What is PostgreSQL?
The data type of keys and values is a string. The PostgreSQL hstore data type is a similar dictionary we are using with other programming languages; The PostgreSQL hstore is specific to the column. It is not necessary to define the keys beforehand. Explanation: The name of the column whose data type will be store.
As of PostgreSQL 9.0, hstore uses a different internal representation than previous versions. This presents no obstacle for dump/restore upgrades since the text representation (used in the dump) is unchanged. In the event of a binary upgrade, upward compatibility is maintained by having the new code recognize old-format data.
PL/pgSQL can't detect variables inside a string literal. You need to use the "constructor" method of the hstore
type to pass a variable:
UPDATE files
SET details = hstore('new_users', p_new_user_count)
where id = v_file_id;
If p_new_user_count
is defined as a number (rather than a varchar
or text
) you need to cast this to a text value:
UPDATE files
SET details = hstore('new_users', p_new_user_count::text)
where id = v_file_id;
Edit after the question was changed:
To do this for multiple variables you can either concatenate two hstore values:
details = hstore('new_users', p_new_user_count::text)||hstore('post_count', p_post_count::text)
or use arrays:
details = hstore(array['new_users','post_count'], array[p_user_count, p_post_count]::text[]);
This is all documented in the manual: http://www.postgresql.org/docs/current/static/hstore.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With