简体   繁体   English

使用雪花中的合并将值插入表并根据条件删除行

[英]Inserting values into a table and delete rows based on a condition using merge in snowflake

I have a table with DBName, SCName, Number.我有一个包含 DBName、SCName、Number 的表。 I wrote a procedure that inserts the DBName, SCName into the table and deletes a row when a Number is 0. I used merge to avoid duplicates and insert based on the condition but I don't understand how to delete a row when a Number=0.我写了一个程序,将 DBName、SCName 插入表中,并在 Number 为 0 时删除一行。我使用合并来避免重复并根据条件插入,但我不明白如何在 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
------------------------

Here is my Procedure:这是我的程序:

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';
    $$;

I didn't understand in which case (MATCHED / NOT MATCHED) the rows with '0' should be deleted from the target table.我不明白在哪种情况下(匹配/不匹配)应该从目标表中删除带有“0”的行。

But in general you have only can use DELETE in the MATCH-case:但一般来说,您只能在 MATCH 情况下使用 DELETE:

when matched and number=0 then delete

It is important to avoid a nondeterministic result for the merge (see link below under "Duplicate Join Behavior").避免合并的不确定结果很重要(请参阅下面“重复连接行为”下的链接)。 Solution therefor is to also add "and number!=0" to your "when matched then update"-clause.为此的解决方案是还将“and number!=0”添加到您的“匹配时然后更新”子句中。

More infos: https://docs.snowflake.com/en/sql-reference/sql/merge.html更多信息: https : //docs.snowflake.com/en/sql-reference/sql/merge.html

EDIT: I posted wrong information.编辑:我发布了错误的信息。 For MATCH you can Delete and Update, for NOT MATCH you can INSERT.对于 MATCH,您可以删除和更新,对于 NOT MATCH,您可以插入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM