主键违规约束

时间:2010-10-01 12:54:09

标签: asp.net sql sql-server ado.net

string sqlInsert = "Insert into account_details(
     account_number,
     account_type,
     transfer_access_code,
     account_balance,
     customer_id) 
SELECT 
     account_number,
     account_type,
     transfer_access_code,
     account_balance,
     customer_id 
from customer_details";

此查询仅从客户详细信息(table1)中获取数据并将其插入其他table2(account_details)

第一次触发此查询时,它可以正常工作

但第二次发射时显示错误 违反PRIMARY KEY约束'PK_account_details'。无法在对象'dbo.account_details'中插入重复键。

任何想法跳过(account_details)table1中的现有数据并在下一行中插入新数据

3 个答案:

答案 0 :(得分:5)

使用LEFT JOIN可以排除account details表中已存在的所有行。替代方案(可能更快)是使用NOT EXISTS

使用LEFT JOIN

INSERT INTO account_details (
    account_number
    , account_type
    , transfer_access_code
    , account_balance
    , customer_id) 
SELECT  account_number
        , account_type
        , transfer_access_code
        , account_balance
        , customer_id 
FROM    customer_details cd
        LEFT OUTER JOIN account_details ad ON ad.Account_number = cd.account_number
WHERE   ad.account_number IS NULL        

使用NOT EXISTS

INSERT INTO account_details (
    account_number
    , account_type
    , transfer_access_code
    , account_balance
    , customer_id) 
SELECT  account_number
        , account_type
        , transfer_access_code
        , account_balance
        , customer_id 
FROM    customer_details cd
WHERE   NOT EXISTS (
          SELECT   * 
          FROM     account_details 
          WHERE    account_number = cd.account_number)

答案 1 :(得分:4)

假设Account_Number是主键,这应该起作用

string sqlInsert = "Insert into account_details(
     account_number,
     account_type,
     transfer_access_code,
     account_balance,
     customer_id) 
SELECT 
     cd.account_number,
     cd.account_type,
     cd.transfer_access_code,
     cd.account_balance,
     cd.customer_id 
from customer_details cd
left outer join account_details ad
    on cd.account_number = ad.account_number
where ad.account_number is NULL";

答案 2 :(得分:0)

INSERT INTO account_details (ad.account_number, ad.account_type, 
    ad.transfer_access_code, ad.account_balance, ad.customer_id) 
SELECT cd.account_number, cd.account_type, 
    cd.transfer_access_code, cd.account_balance, cd.customer_id
FROM customer_details cd
LEFT OUTER JOIN account_details ad 
    ON cd.account_number = ad.account_number 
WHERE ad.account_number is NULL