雪花:IFNULL不能在INSERT VALUES的subSQL中使用

时间:2019-03-27 22:07:21

标签: sql-insert snowflake-datawarehouse ifnull

尝试在INSERT VALUES子句中使用IFNULL时遇到编译错误。

SQL:

"table": "name",
"inserts": [
    {
        "fields": [
            "id",
            "name"
        ],
        "values": [
            1,
            "National Monument"
        ]
    }
]

错误

INSERT INTO widgets 
VALUES 
(12, (select ifnull(max(c), 0)+1 from DCSN_Testing where c = 1), 444)

1 个答案:

答案 0 :(得分:1)

通常情况下,我在INSERT的VALUES语句中没有子选择,实际上我不记得在编写SQL的所有年份中都做了一次。

也就是说,我建议您尝试以下示例,将其称为“ INSERT INTO SELECT”或Snowflake文档称为“使用查询的单行插入”,该IMO是编写SQL的简单方法。

注意:这已在Snowflake上进行了测试。

-- this is a simple test table, represents your 
--   DCSN_Testing table, results are a value of 5
SELECT IFNULL(MAX(id), 0)+1 FROM first_names;

-- create a test table
DROP TABLE stackoverflow_55387209;
CREATE TABLE stackoverflow_55387209(id NUMBER, 
    new_id NUMBER, other_id  NUMBER);

-- test for your error, results confirm your findings
INSERT INTO stackoverflow_55387209 (id, new_id, other_id)
VALUES (12, (select max(ifnull(id, 0) + 1)  FROM first_names), 444) ;
results:  
SQL compilation error: Invalid expression [(SELECT MAX((NULLABILITY_EXTERNAL(FIRST_NAMES.ID)) + 1) AS "NEW_ID" 
FROM FIRST_NAMES AS FIRST_NAMES)] in VALUES clause

-- rewrite to "INSERT INTO SELECT" type of SQL Query, as described in documentation
--      https://docs.snowflake.net/manuals/sql-reference/sql/insert.html#single-row-insert-using-a-query
INSERT INTO stackoverflow_55387209
SELECT 12, MAX(IFNULL(id, 0) + 1), 444  FROM first_names ;
results:  number of rows inserted = 1