我有一个包含DBName,SCName,Number的表。我编写了一个过程,该过程将DBName,SCName插入表中,并在Number为0时删除一行。我使用merge来避免重复并根据条件插入,但是我不明白如何在Number =时删除行0。
------------------------
|DBName| SCName| Number|
| DB1 | SC1 | 1 |
| DB2 | SC2 | 0 | <-- Need to delete row
| DB2 | SC3 | 2 |
| DB2 | SC1 | 4 |
| DB3 | SC4 | 0 | <-- Need to delete row
------------------------
这是我的程序:
CREATE TABLE TABL(DBName VARCHAR, SCName VARCHAR); // creating table
CREATE OR REPLACE PROCEDURE repo(DB VARCHAR,SC VARCHAR)
RETURNS string
LANGUAGE JAVASCRIPT
AS
$$
//inserting values into table using merge
//if values are already present and Number = 0 then I need to delete row
var sql_command = `merge into TABL as t
using (SELECT :1 as database,:2 as schema) as s
on t.DBName = s.database
and t.SCName = s.schema
when matched then update
set t.DBName = t.DBName
when not matched then insert
(DBName, SCName) VALUES (:1,:2)`;
snowflake.execute({sqlText: sql_command, binds: [DB, SC]});
return 'success';
$$;
答案 0 :(得分:1)
我不知道在哪种情况下(已匹配/未匹配)应从目标表中删除具有'0'的行。
但是通常情况下,您只能在MATCH情况下使用DELETE:
when matched and number=0 then delete
重要的是避免合并的不确定结果(请参见下面的“重复连接行为”下的链接)。解决方案是在“匹配后更新”子句中也添加“和数字!= 0”。
更多信息:https://docs.snowflake.com/en/sql-reference/sql/merge.html
编辑:我发布了错误的信息。对于MATCH,您可以删除和更新,对于NOT MATCH,则可以插入。