具有insert语句的Firebird CTE结果数据集

时间:2013-09-13 11:21:00

标签: sql firebird common-table-expression

我确实遇到以下代码的困难,我找不到将insert语句放在该代码中的位置,它将从CTE插入返回的值。

insert into ntm (num,comb,0,0,0,0,0,0,0,0,0,0,0,0)
with CTE as (
  SELECT a.ELM_NUM as num, 
         a.N_1 as N1,
         (trim('1.4*'||a.COMBO)||' + ' || '1.6*'||b.COMBO) as com2,
         b.ELM_NUM as num2 
    FROM NTM a cross join ntm b 
    where ((a.Combo='dead' and b.combo='live') or (a.Combo='dead' and b.combo='live')) and a.ELM_NUM=b.ELM_NUM) 

  select num, num2, trim(trim(com2)||' + '||trim(d.combo)), N1, 1.4*N1
    from CTE cross join ntm d
    where (d.elm_num = cte.num) and (position('X',combo)>0 or position('Y',combo)>0 ) 
FlameRobin Engine引发的错误“令牌未知 - 第1行,第27列 0

CREATE TABLE NTM
(
ELM_NUM Integer NOT NULL,
COMBO Char(40) NOT NULL,
N_1 Double precision,
N_2 Double precision,
V2_1 Double precision,
V2_2 Double precision,
V3_1 Double precision,
V3_2 Double precision,
M2_1 Double precision,
M2_2 Double precision,
M3_1 Double precision,
M3_2 Double precision,
MT_1 Double precision,
MT_2 Double precision
);

1 个答案:

答案 0 :(得分:1)

您可以通过在select语句(包括INSERT INTO <table> (<column>[, <column>]*))之前添加WITH来插入select语句的结果。所以如果您有疑问:

WITH a AS (
    SELECT 4 AS ID, 'Item 4' AS NAME FROM RDB$DATABASE
) 
SELECT ID, NAME 
FROM a

您想插入包含ITEMS列和ID列的表NAME

INSERT INTO ITEMS (ID, NAME) 
WITH a AS (
    SELECT 4 AS ID, 'Item 4' AS NAME FROM RDB$DATABASE
) 
SELECT ID, NAME 
FROM a

这适用于Firebird 2.5,但我认为它也适用于Firebird 2.1。

根据您的修改

您的语法完全错误:insert into ntm (num,comb,0,0,0,0,0,0,0,0,0,0,0,0)无效:您在表num中没有列combntm,并指定0作为列名是非法的。您似乎将INSERT列表与值列表混淆。

INSERT的语法是:

INSERT INTO <object> [(col [, col …])]
{VALUES (<val> [, <val> …]) | <select_expr>}

您尝试使用以下内容:

INSERT INTO <object> (<val> [, <val> …])
<select_expr>

假设您只想从select中插入numELM_NUM}和trim(trim(com2)||' + '||trim(d.combo))COMBO)列,您应该使用:

insert into ntm (ELM_NUM,COMBO)
with CTE as (
    SELECT a.ELM_NUM as num, 
         a.N_1 as N1,
         trim('1.4*'||a.COMBO)||' + ' || '1.6*'||b.COMBO as com2,
         b.ELM_NUM as num2 
    FROM NTM a cross join ntm b 
    where (a.Combo='dead' and b.combo='live' or a.Combo='dead' and b.combo='live') and a.ELM_NUM=b.ELM_NUM
) 
select num, trim(trim(com2)||' + '||trim(d.combo))
from CTE cross join ntm d
where d.elm_num = cte.num and (position('X',combo) > 0 or position('Y',combo) > 0)

请注意,我从select中删除了其他列,因为您没有插入这些列(选择列表中的列数必须与插入列列表中的列数相匹配)。

如果您希望其余列为0,则需要在表定义中添加DEFAULT 0,或者需要列出所有列并在选择列表中添加0值每个附加列。