I need to write a function that will transform the results of a column called "store_id" in a table. I want to transform the integer 1 into "Store 1" and 2 into "Store 2", but I get errors no matter what I enter.
I tried:
CREATE OR REPLACE FUNCTION transform_store_id()
RETURNS VOID AS $$
BEGIN
UPDATE detailed_sales
SET store_id = CASE store_id
WHEN 1 THEN 'store 1'
WHEN 2 THEN 'store 2'
ELSE store_id::text
END;
END;
$$
LANGUAGE plpgsql;
But I get "ERROR: column "store_id" is of type integer but expression is of type text"
So, I tried incorporating CAST and TO_CHAR with varying errors.
3
Answers
You need first change the column type
fiddle
You can add a new column with the text data type and update it with the required values in order to change the "store_id" column in your table. try the following code. In this code the original "store_id" column is preserved while a new "store_name" column is created and updated.
Hope it works 🙂
Other answers have demonstrated that there is no need for a function at all.
Another approach might be to use
GENERATED
(manual) – akaCOMPUTED
,DERIVED
and also confusingly,VIRTUAL
, columns (all of the code below is available on the fiddle here).Populate:
Add our
GENERATED
column:And, without further ado, we run:
Result:
And our
store 1
,store 2
, &c. "magically" appear!The
PG_TYPEOF()
(manual) function is, of course, not necessary – just for demonstration purposes!Note that the
STORED
keyword is compulsory – most servers have two storage modes forGENERATED
columns –STORED
(on disk) andVIRTUAL
(computed on the fly – i.e. when requested) – hence the remark about calling the column itselfVIRTUAL
being confusing.