(combine CASE and UPDATE statements) UPSERT in Amazon Redshift

时间:2017-10-12 10:15:34

标签: if-statement sql-update amazon-redshift sql-insert

I know with Azure its possible to combine a IF x THEN UPDATE ELSE INSERT, is it possible to do the same thing with Redshift SQL?

I am currently trying this code:

SELECT source,
CASE WHEN (SELECT 1 FROM state WHERE name = 
'out_dev' AND environment = 'dev') > 0
THEN
(UPDATE state SET source='new source')
ELSE (
INSERT state (source, name, load_time, hash, environment)
VALUES ('test', 'out_dev', '2017-10-12 01:14:38', '"f324f873b05d0792a3192bc28f466835"', 'dev'))
END
FROM state

This returns the error:

[Amazon](500310) Invalid operation: syntax error at or near "state" 

Position: 132;

(UPDATE state SET source='new source')

I am new to Redshift so forgive if I am not seeing something obvious.

1 个答案:

答案 0 :(得分:0)

要回答您的第一个问题,Redshift SQL没有像#34; If - Then - Else"这样的流量控制语句,所以这不可能是您尝试这样做的方式

对于您的具体示例,它并不是很清楚您要尝试实现的目标,但是如果您想要有条件地插入行来进行"测试"如果它不存在,那么你可以做类似的事情:

INSERT INTO state (source, name, load_time, hash, environment)
SELECT 
  'test', 
  'out_dev', 
  '2017-10-12 01:14:38', 
  '"f324f873b05d0792a3192bc28f466835"', 
  'dev'
WHERE NOT EXISTS 
  (
   SELECT 1 FROM state 
   WHERE name = 'out_dev' AND environment = 'dev'
  )
;