3

I have two tables, sprockets and cogs.

create table sprockets(
    id NUMBER
);

INSERT into sprockets VALUES (4);
INSERT into sprockets VALUES (8);
INSERT into sprockets VALUES (15);
INSERT into sprockets VALUES (16);
INSERT into sprockets VALUES (23);
INSERT into sprockets VALUES (42);

create table cogs(
    id NUMBER
);

I want to take some ids from sprockets and put them into cogs.

insert into cogs select id from sprockets s where s.id < 40 and MOD(s.id, 3) != 0;

This adds sprockets 4, 8, 16, 23 to cogs as expected.

4 rows inserted

As my sprocket making business grows, the business logic for determining which sprockets require cogs will become much more complicated. So I would like to use a sequence of temporary tables that filter out non-candidate sprockets. I believe this is more maintainable than a one line statement with no comments.

--sprockets with ids greater than 40 are too big to frob, 
--so it's impossible to weld a cog to them
with frobbableSprockets as(
    select id from sprockets where sprockets.id < 40
),

--non-greppable sprockets have built-in harmonic oscillators, 
--so cogs are not required
greppableFrobbableSprockets as(
    select id from frobbableSprockets f where MOD(f.id,3) != 0
),

--not pictured: more filtering using arcane business logic, 
--including but not limited to:
--whether it is raining on a tuesday,
--and if the moon is in the seventh house.

--sprockets with ids less than 3 are from the legacy system and already have cogs
sprocketsRequiringCogs as(
    select id from greppableFrobbableSprockets f where f.id > 3
)

insert into cogs select id from sprocketsRequiringCogs

This code is relatively readable, but unfortunately it does not work!

insert into cogs select id from sprocketsRequiringCogs 
Error at Command Line:18 Column:2
Error report:
SQL Error: ORA-00928: missing SELECT keyword

If I change the last line to select id from sprocketsRequiringCogs, there is no error, so I know the problem must be in the insert statement and not in the declaration of the temporary tables.

The one-line insert statement works, and the multi-line insert statement does not work. The only difference I see is that the latter is getting its values from a temporary table.

Why can't I insert rows from a temporary table?

4

3 回答 3

3

这是一个猜测,我现在无法尝试,但这可能可行:

insert into cogs
with frobbableSprockets as(
    select * from sprockets where sprockets.id < 40
),
...
select * from sprocketsRequiringCogs
于 2012-08-23T19:23:34.607 回答
0
 insert into cogs (Id) select Id from sprocketsRequiringCogs 
于 2012-08-23T19:02:50.123 回答
0

尝试用内联视图替换 WITH 子句,即在 from (select) 中使用您的 select 语句。

于 2012-08-23T19:11:23.223 回答