无法理解如何在BEGIN和END中使用EXCEPTION

时间:2018-05-14 22:36:21

标签: sql postgresql

我是Postgres的新手,我正在尝试为以下查询的结果返回null时创建一个测试,但我似乎无法做到正确。我一直收到以下错误

ERROR:  syntax error at or near "WITH"
LINE 20: WITH expected (tran_id, sell_chan, total) AS (VALUES (3, 'St...

当我尝试运行以下代码时。请注意,如果我删除BEGIN和END以及EXCEPTION部分,其他所有内容都可以正常运行并获得预期的空查询。

-- create test database
DROP TABLE IF EXISTS test_sales;
CREATE TABLE test_sales(
  tran_id INT PRIMARY KEY,
  chan_c VARCHAR(1),
  total FLOAT
);


-- populate test database
INSERT INTO test_sales VALUES (1, 'S', 99.99);
INSERT INTO test_sales VALUES (2, 'O', 99.99);
INSERT INTO test_sales VALUES (3, 'S', 100);
INSERT INTO test_sales VALUES (4, 'O', 100);
INSERT INTO test_sales VALUES (5, 'P', 99.99);
INSERT INTO test_sales VALUES (6, 'P', 100);

BEGIN
WITH expected (tran_id, sell_chan, total) AS (VALUES (3, 'Store', 100), (4, 'Online',100), (6,'Other',100))
SELECT tran_id, sell_chan, total INTO my_temp FROM (SELECT * FROM expected) AS q1 EXCEPT (SELECT tran_id,
                CASE chan_c
                WHEN 'S' THEN 'Store'
                WHEN 'O' THEN 'Online'
                ELSE 'Other'
                END sell_chan,
                total
                FROM test_sales AS q2 WHERE q2.total>=100) EXCEPTION WHEN NO_DATA_FOUND THEN NULL; 


END;

1 个答案:

答案 0 :(得分:1)

  • 必须使用DO;
  • 完成匿名阻止
  • 要插入临时表,首先必须创建它。
  • 语法为INSERT INTO TABLE <table> SELECT ...而非SELECT ... INTO <table>
  • EXCEPTION需要一个它所属的块。
  • 关于您的意见的附注:表格不是数据库!

尝试:

-- create test table
DROP TABLE IF EXISTS test_sales;
CREATE TABLE test_sales(
  tran_id INT PRIMARY KEY,
  chan_c VARCHAR(1),
  total FLOAT
);


-- populate test table
INSERT INTO test_sales VALUES (1, 'S', 99.99);
INSERT INTO test_sales VALUES (2, 'O', 99.99);
INSERT INTO test_sales VALUES (3, 'S', 100);
INSERT INTO test_sales VALUES (4, 'O', 100);
INSERT INTO test_sales VALUES (5, 'P', 99.99);
INSERT INTO test_sales VALUES (6, 'P', 100);

DROP TABLE IF EXISTS my_temp;
CREATE TEMPORARY TABLE my_temp AS SELECT * FROM test_sales WHERE 1 <> 1;

DO
$$
BEGIN
  BEGIN
    WITH expected (tran_id, sell_chan, total) AS (VALUES (3, 'Store', 100), (4, 'Online',100), (6,'Other',100))
    INSERT INTO my_temp
    SELECT tran_id, sell_chan, total  FROM (SELECT * FROM expected) AS q1 EXCEPT (SELECT tran_id,
                    CASE chan_c
                    WHEN 'S' THEN 'Store'
                    WHEN 'O' THEN 'Online'
                    ELSE 'Other'
                    END sell_chan,
                    total
                    FROM test_sales AS q2 WHERE q2.total>=100);
  EXCEPTION WHEN NO_DATA_FOUND THEN
    NULL;
  END;
END;
$$
LANGUAGE plpgsql;