[英]AWS Redshift IF-ELSE Logic
我基本上想在 Redshift 中做以下事情,但由於 Redshift 不支持程序語句,我不確定如何實現我的目標:
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
參數 1 是用戶 ID,參數 2 是用戶名
在紅移中實現這一目標的最佳方法是什么? 感謝您提前提供任何幫助
跑步:
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
定義 true 僅用於演示目的。 我收到以下錯誤:
---> syntax error at or near "case"
LINE 2: case when 1=1
我看到exists
紅移支持,所以也許這會起作用
/* 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)
您需要使用與if-else
類似的CASE
表達式。
case when new_record = existing_record
update existing_record
else insert new_record
end
如果我沒記錯的話,您似乎正在嘗試進行更新。 您可以在 redshift 上使用合並功能嗎? 在進行插入/更新之前,您需要使用臨時表來保存一些值。
以下是 redshift 文檔中的一些示例
https://docs.aws.amazon.com/redshift/latest/dg/merge-examples.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.