Say I have a table with two columns
first is called "temp_status", which is an int with values, 0,1,2,3,4 and the other is called "status" which is of type enum, with values, "Enum1", "Enum2", "Enum3", "Enum4", "Enum5",
I want to assign values to the "status" column based on "temp_status" column. I did the following and got the following error:
UPDATE "Table"
SET "status" =
CASE
WHEN "temp_status" = 0 THEN 'Enum1'
WHEN "temp_status" = 1 THEN 'Enum2'
WHEN "temp_status" = 2 THEN 'Enum3'
WHEN "temp_status" = 3 THEN 'Enum4'
WHEN "temp_status" = 4 THEN 'Enum5'
ELSE 'Enum1' -- default value
END
WHERE "temp_status" IN (0, 1, 2, 3, 4);
I got this error;
ERROR: column "status" is of type "MyEnumName" but expression is of type text
HINT: You will need to rewrite or cast the expression.
The enum values match so I am wondering how I need to do the casting here
CodePudding user response:
You're just missing a cast to the enum strings, e.g.
UPDATE t
SET status =
CASE
WHEN temp_status = 0 THEN 'Enum1'::MyEnumName
WHEN temp_status = 1 THEN 'Enum2'::MyEnumName
WHEN temp_status = 2 THEN 'Enum3'::MyEnumName
WHEN temp_status = 3 THEN 'Enum4'::MyEnumName
WHEN temp_status = 4 THEN 'Enum5'::MyEnumName
ELSE 'Enum1' -- default value
END
WHERE temp_status IN (0, 1, 2, 3, 4);
Note: the default value will never be reached, as the values of temp_status
are constraint to values that are already mapped in the case conditions (0, 1, 2, 3, 4) .
However, since your enums can be easily mapped to the column temp_status
, you can substantially simplify the update by concatenating 'Enum'
and the content of temp_status
:
UPDATE t
SET status = ('Enum'||temp_status 1)::MyEnumName
WHERE "temp_status" IN (0, 1, 2, 3, 4);
Demo: db<>fiddle