I basically want to do the following thing in Redshift but since Redshift does not support procedural statements I am unsure how to achieve my goal:
IF EXISTS (select username,accountnumber from table where username={1})
THEN
IF {0} NOT IN accountnumber
update table set accountnumber =
accountnumber+=',{0}' where username='{1}'
END IF
ELSE
insert into table values({1},{0});
END IF
With param 1 being a user id and param 2 being a username
What would be the best way to achieve this in redshift? Thanks for any help in advance
Running:
CREATE TABLE IF NOT EXISTS table (account_number
varchar(100), username varchar(50));
case when true
update table set accountnumber = accountnumber+=',{0}'
where username='{1}'
else insert into table values ('{0}','{1}')
end
defining true is just for demo purposes. I am getting the following error:
---> syntax error at or near "case"
LINE 2: case when 1=1
I see that redshift supports exists
so maybe this will work
/* if the row is there it'll update it. If not it won't */
UPDATE Table Set Field='NewValue' Where KeyValue=1
/* if the row is not there it'll insert it */
INSERT INTO Table (KeyValue,Field1,Field2)
SELECT 1,'NewValue','NewValue'
WHERE NOT EXISTS (SELECT * FROM Table WHERE KeyValue=1)
You need to use CASE
expression which works similarly to if-else
.
case when new_record = existing_record
update existing_record
else insert new_record
end
If I'm not mistaken, it seems like you are trying to do an upsert. You can make use of merge functionality on redshift? You will need to use a temporary table for holding some of the values before you do the insert/update.
Here are some examples from redshift documentation
https://docs.aws.amazon.com/redshift/latest/dg/merge-examples.html
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.