防止插入重复的行

时间:2010-08-02 00:03:54

标签: sql sql-server tsql

我正在尝试使用SQL insert语句将行从一个数据库中的表迁移到另一个数据库中的表。该语句有效,直到我在目标表上添加唯一索引,此时我正在努力获取insert语句以排除重复项。这是我应该工作的:

INSERT INTO [MyDB].[dbo].[HPB] (
    [HPID],
    [BusinessID]
)
SELECT 
    PersonId = (SELECT ID FROM [MyDB].[dbo].[HP] WHERE PersonID = lPersonId),
    lBusinessId
FROM [MyOriginalDB].[dbo].[tblEmployment]
WHERE
    lPersonId in (SELECT PersonID FROM [MyDB].[dbo].[HP])
AND
    lBusinessId in (SELECT ID FROM [MyDB].[dbo].[Business])
AND 
   NOT EXISTS (SELECT * FROM [MyDB].[dbo].[HPB] WHERE 
     [HPID] = (SELECT ID FROM [MyDB].[dbo].[HP] WHERE PersonID = lPersonId) 
     AND [BusinessID] = lBusinessId)

HPB表的架构是:

CREATE TABLE [dbo].[HPB](
   [ID] [int] IDENTITY(1,1) NOT NULL,
   [HPID] [int] NOT NULL,
   [BusinessID] [int] NOT NULL,
   CONSTRAINT [PK_HealthProfessionalBusiness] PRIMARY KEY CLUSTERED)

唯一索引位于[MyDB]。[dbo]。[HPB]列表(HPID,BusinessID)

当我运行插入时,我收到有关重复行插入的错误,我无法理解为什么下面的SQL不会排除重复项。

 NOT EXISTS (SELECT * FROM [MyDB].[dbo].[HPB] WHERE 
     [HPID] = (SELECT ID FROM [MyDB].[dbo].[HP] WHERE PersonID = lPersonId) 
     AND [BusinessID] = lBusinessId)

2 个答案:

答案 0 :(得分:2)

使用:

INSERT INTO [MyDB].[dbo].[HPB] 
  ([HPID], [BusinessID])
SELECT DISTINCT
       h.id,
       e.lbusinessid
  FROM [MyOriginalDB].[dbo].[tblEmployment] e
  JOIN [MyDB].[dbo].[HP] h ON h.personid = e.lpersonid
 WHERE e.lbusinessid in (SELECT ID FROM [MyDB].[dbo].[Business])
   AND NOT EXISTS (SELECT NULL 
                     FROM [MyDB].[dbo].[HPB] hb
                    WHERE hb.businessid = e.lbusinessid
                      AND hb.hpid = h.id)

答案 1 :(得分:2)

Insert MyDB.dbo.HPB( HPID, BusinessID )  
Select HP.ID, E.IBusinessID  
From [MyOriginalDB].[dbo].[tblEmployment] As E
    Join [MyDB].[dbo].[HP] As HP
        On HP.PersonId = E.IPersonID
    Join [MyDB].[dbo].[Business] As B
        On B.ID = E.IBusinessID
    Left Join [MyDB].[dbo].[HPB] As HPB
        On HPB.BusinessID = E.IBusinessID
            And HPB.PersonID = E.IPersonId
Where HPB.ID Is Null
Group By HP.ID, E.IBusinessID