我有下面的代碼BULK INSERT
一個問題:違反使用鮮明
CREATE TABLE [dbo].[SubscribersDeliveries]
(
[Status] [tinyint] NOT NULL,
[LimitReached] [bit] NOT NULL,
[IdSubscriber] [int] NOT NULL,
[ContentType] [smallint] NOT NULL,
[UTCDate] [date] NOT NULL,
CONSTRAINT [PK_SubscribersDeliveries] PRIMARY KEY CLUSTERED
([Status] ASC, [LimitReached] ASC, [IdSubscriber] ASC)
) ON [PRIMARY]
INSERT INTO dbo.SubscribersDeliveries
(IdSubscriber,
Status,
LimitReached,
ContentType,
UTCDate)
SELECT DISTINCT s.IdSubscriber,
CASE cdoi.Status
WHEN 0 THEN 0
WHEN 1 THEN 1
WHEN 2 THEN 2
WHEN 3 THEN 1
WHEN 4 THEN 1
WHEN 5 THEN 1
WHEN 6 THEN 1
WHEN 7 THEN 1
WHEN 8 THEN 2
END AS Status,
CASE
WHEN CONDITION1 THEN 1
WHEN CONDITION2 THEN 1
WHEN CONDITION3 THEN 1
ELSE 0
END LimitReached,
cam.ContentType,
@Date
FROM Tables join
請注意,我使用的是DISTINCT
條款。此腳本返回以下錯誤:
Violation of PRIMARY KEY constraint 'PK_SubscribersDeliveries'. Cannot insert duplicate key in object 'dbo.SubscribersDeliveries'.
任何人都可以幫助我嗎?
編輯:
當內試圖組,把我的錯誤,因爲需要通過組也cdoi.IdDeliveryStatus,我需要組由CASE結果。
CASE cdoi.IdDeliveryStatus
WHEN 0 THEN 0
WHEN 1 THEN 1
WHEN 2 THEN 2
WHEN 3 THEN 1
WHEN 4 THEN 1
WHEN 5 THEN 1
WHEN 6 THEN 1
WHEN 7 THEN 1
WHEN 8 THEN 2
END AS IdDeliveryStatus
現在我試圖封裝所有的查詢
SELECT result.IdSubscriber,
result.IdDeliveryStatus,
result.LimitReached,
result.ContentType,
@Date
FROM (SELECT distinct s.IdSubscriber,
CASE cdoi.IdDeliveryStatus
WHEN 0 THEN 0
WHEN 1 THEN 1
WHEN 2 THEN 2
WHEN 3 THEN 1
WHEN 4 THEN 1
WHEN 5 THEN 1
WHEN 6 THEN 1
WHEN 7 THEN 1
WHEN 8 THEN 2
END AS IdDeliveryStatus,
CASE
WHEN cdoi.IdDeliveryStatus = 0
AND u.Limit1 > 0
AND (ISNULL(s.Limit1, 0) + 1 >= u.Limit1) THEN 1
WHEN cdoi.IdDeliveryStatus IN (1, 3, 4, 5,
6, 7)
AND (ISNULL(s.Limit1, 0) + 1 >= u.Limit1) THEN 1
WHEN cdoi.IdDeliveryStatus IN (2, 8)
AND (ISNULL(s.Limit2, 0) + 1 >= u.Limit2) THEN 1
ELSE 0
END LimitReached,
cam.ContentType ContentType
FROM @tempCampaigns t
JOIN Campaign cam WITH (NOLOCK)
ON t.idcampaign = cam.IdCampaign
JOIN DBO.Subscriber s WITH (NOLOCK)
ON s.IdUser = cam.IdUser
JOIN DBO.[User] u WITH (NOLOCK)
ON s.idUser = u.idUser
JOIN DBO.Deliveries cdoi WITH (NOLOCK)
ON cdoi.IdSubscriber = s.IdSubscriber
AND cam.IdCampaign = cdoi.IdCampaign
WHERE s.IdSubscribersStatus < 3
) result
GROUP BY result.IdSubscriber,
result.IdDeliveryStatus,
result.LimitReached,
result.ContentType,
result.IdSubscribersStatus
在內部查詢中使用DISTINCT,而在外面,通過使用德集團,但繼續將複製!
'distinct'在選擇列表中的** all **列上運行。由於你的'select'包含比主鍵更多的列,可能會發生重複。 – 2014-08-29 14:10:53
你能告訴我們完整的查詢嗎?您需要添加一個「GROUP BY」子句才能擁有唯一的IdSubscriber + Status + LimitReached。 – 2014-08-29 14:13:45