2014-02-15 49 views
3

這是我的查詢,我要插入這應該從另一個表中選擇的值:插入並選擇組合不工作

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

...但它給我一個錯誤:

Msg 515, Level 16, State 2, Line 1 Cannot insert the value NULL into column 'customer_id', table 'kohinoor_rdfd.kohin_plan.payment_details_kohin'; column does not allow nulls. INSERT fails. The statement has been terminated.

當我嘗試以下查詢:

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 ')'. 
+1

親愛的朋友檢查我的文章會爲工作你 – Developerzzz

+0

只需刪除'值' – Hoh

回答

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

你不需要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

親愛的朋友,當你在一個表從另一個表中插入值或然後inseting使用select你不要有spacity了「值」關鍵詞

那麼簡單做以下

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