根据Redshift WITH Clause documentation,您可以使用带有INSERT INTO...SELECT
语句的WITH子句。但是在测试时,我收到以下错误。这是不可能的,还是我的语法错了?
CREATE TABLE TestCTEInsert (SomeTimestamp TIMESTAMP);
WITH CTE AS
(SELECT GETDATE() as SomeTimestamp)
INSERT INTO TestCTEInsert
(SomeTimestamp) SELECT SomeTimestamp from CTE;
错误:42601:语法错误在或附近"插入"
有趣的是,它确实支持插入新表格,即
WITH CTE AS
(SELECT GETDATE() as SomeTimestamp)
INSERT SomeTimestamp INTO NewTable
SELECT SomeTimestamp from CTE;
命令成功完成(受影响的一行)
编辑:要确认,使用INTEGER
列而不是TIMESTAMP
时会出现同样的错误:
CREATE TABLE TestCTE (SomeInt INTEGER);
WITH CTE AS
(SELECT 1 as SomeInt)
INSERT INTO TestCTEInsert
SELECT SomeInt from CTE;
错误:42601:语法错误在或附近"插入"
答案 0 :(得分:20)
尝试将CTE放入插入物中(不确定是否胜过该点)
INSERT INTO TestCTEInsert
WITH CTE AS
(SELECT CURRENT_TIMESTAMP as SomeTimestamp)
SELECT SomeTimestamp from CTE;
答案 1 :(得分:7)
;
终止一个语句,所以它需要在语句的末尾,而不是在中间的某个地方:
您可以通过两种方式执行此操作,使用create table as select
create table TestCTEInsert
as
WITH CTE AS
(
SELECT current_timestamp as SomeTimestamp
)
SELECT SomeTimestamp
from CTE; -- ; only at the end
或分两步:
CREATE TABLE TestCTEInsert (SomeTimestamp TIMESTAMP); -- end this with a ;
insert into TestCTEInsert
WITH CTE AS
(
SELECT current_timestamp as SomeTimestamp
)
SELECT SomeTimestamp
from CTE; -- ; only at the end
以上是在一个vanilla Postgres安装上运行的,我无法访问RDS
答案 2 :(得分:1)
将脚本更改为此
CREATE TABLE TestCTE (SomeInt INTEGER)
WITH CTE AS (SELECT 1 as SomeInt)
INSERT INTO TestCTE SELECT SomeInt from CTE;
答案 3 :(得分:1)
试试这个
CREATE TABLE TestCTE (SomeInt INTEGER)
;WITH CTE AS
(SELECT 1 as SomeInt)
INSERT (SomeInt) INTO TestCTE
SELECT SomeInt FROM CTE;