在SQL Server中从另一个表数据插入一个表数据时绕过重复记录

时间:2016-08-02 03:01:18

标签: sql sql-server sql-server-2012

我正在尝试将数据从一个数据库表插入另一个数据库表。这项工作执行得很好,但需要绕过无法插入重复数据。这是我在下面的查询。如何查看重复记录?

library(tidyr)

extract_numeric(testVector)
## [1] 10  6  4 15

- HR_DeviceInOut

;WITH ABC AS (
    SELECT 
    5 AS DeviceID
    , nUserID AS CardNo
    , CONVERT(DATE, dbo.fn_ConvertToDateTime(nDateTime)) AS InOutDate
    , CONVERT(VARCHAR(8) ,CONVERT(TIME,dbo.fn_ConvertToDateTime(nDateTime))) AS InOutTime
    FROM [BioStar].[dbo].[TB_EVENT_LOG]
)
SELECT * INTO #tempAtten FROM ABC

INSERT [HR].[dbo].[HR_DeviceInOut](DeviceID, CardNo, InOutDate, InOutTime, ShiftprofileID, ExecutedBy)
SELECT DeviceID, CardNo, InOutDate, InOutTime, NULL, NULL
FROM #tempAtten
WHERE #tempAtten.InOutDate = CONVERT(DATE, GETDATE()) AND #tempAtten.CardNo <> 0 

DROP TABLE #tempAtten

- 功能

CREATE TABLE [dbo].[HR_DeviceInOut](
    [id] [bigint] IDENTITY(100000000000001,1) NOT NULL,
    [DeviceID] [nvarchar](20) NULL,
    [CardNo] [nvarchar](20) NOT NULL,
    [InOutDate] [date] NOT NULL,
    [InOutTime] [nvarchar](10) NOT NULL,
    [ShiftprofileID] [tinyint] NULL,
    [ExecutedBy] [int] NULL,
 CONSTRAINT [PK_HR_AttenHistory] PRIMARY KEY CLUSTERED 
(
    [id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

2 个答案:

答案 0 :(得分:1)

假设我理解正确,这是使用not exists的一个选项:

INSERT [HR].[dbo].[HR_DeviceInOut] (DeviceID, CardNo, InOutDate, 
                                    InOutTime, ShiftprofileID, ExecutedBy)
SELECT DeviceID, CardNo, InOutDate, InOutTime, NULL, NULL
FROM #tempAtten t
WHERE t.InOutDate = CONVERT(DATE, GETDATE()) AND 
    t.CardNo <> 0 AND 
    NOT EXISTS (
         SELECT 1
         FROM [HR].[dbo].[HR_DeviceInOut] d
         WHERE t.DeviceID = d.DeviceId AND 
               t.CardNo = d.CardNo AND
               t.InOutDate = d.InOutDate AND 
               t.InOutTime = d.InOutTime
      )

考虑将unique_index添加到那些无法复制的字段中。

答案 1 :(得分:0)

哪个列集使记录唯一,因为我看到某些列是硬编码的

即5 AS DeviceID ...

为临时表和destinationtabel中的其余列创建唯一键,以避免重复。