插入和选择组合不起作用

时间:2014-02-15 11:29:43

标签: sql sql-server-2008

这是我想要插入应从另一个表中选择的值的查询:

insert into payment_details_kohin(installment_no)
 values(
select count(installment_amount)+2  
from kohin_plan.payment_details_insert 
where customer_id='KBP100058'
)

...但它给了我一个错误:

  

消息515,级别16,状态2,行1无法将值NULL插入   列'customer_id',表格   'kohinoor_rdfd.kohin_plan.payment_details_kohin';专栏没有   允许空值。 INSERT失败。声明已经终止。

当我尝试以下查询时:

insert into payment_details_kohin(installment_no)
values(
select count(installment_amount)+2  
from kohin_plan.payment_details_insert 
where customer_id='KBP100058'
)

...它给了我以下错误

Msg 156, Level 15, State 1, Line 2
Incorrect syntax near the keyword 'select'.
Msg 102, Level 15, State 1, Line 3
Incorrect syntax near ')'.

3 个答案:

答案 0 :(得分:2)

您不需要这里的Values子句,只需执行以下操作

INSERT INTO payment_details_kohin(installment_no)
SELECT ISNULL(COUNT(installment_amount), 0) + 2  
FROM kohin_plan.payment_details_insert 
WHERE customer_id = 'KBP100058'

答案 1 :(得分:2)

您的问题是您拥有非NULL客户ID。您还需要将其插入表中:

insert into payment_details_kohin(customer_id, installment_no)
    select customer_id, count(installment_amount)+2  
    from kohin_plan.payment_details_insert 
    where customer_id='KBP100058';

然而,当我看到inserts时,有时真正需要的是更新:

update payment_details_kohin
    set installment_no = (select count(installment_amount) + 2
                          from kohin_plan.payment_details_insert 
                          where payment_details_kohin.customer_id = payment_details_insert.customer_id
                         )
    where customer_id = 'KBP100058';

答案 2 :(得分:1)

亲爱的朋友,当您从另一个表中的一个表中插入值或使用select for inseting时,您不必空间“值”关键字

如此简单,请执行以下操作

INSERT INTO payment_details_kohin(installment_no)
SELECT count(installment_amount) + 2  
FROM kohin_plan.payment_details_insert 
WHERE customer_id = 'KBP100058'