1
我遇到了Insert不存在的問題,而且我不確定MERGE語句是否會更有效或者說我的聲明出了什麼問題。插入不存在的地方違反PRIMARY KEY
我已經存在查看並需要將此視圖的新記錄插入表中。
表的樣子:
CREATE TABLE [dbo].[ser_number_all]
(Serialnumber nvarchar(100) PRIMARY KEY,
TypeName nvarchar(max),
Date datetime,
Parent_Serialnumber nvarchar(100),
JobNumber nvarchar(30),
ProductNode hierarchyid,
);
INSERT語句如下:
insert into [dbo].[ser_number_all]
(Serialnumber
, TypeName
, Date
, Parent_Serialnumber
, JobNumber
, ProductNode)
select Serialnumber
, TypeName
, Date
, Parent_Serialnumber
, JobNumber
, ProductNode
from dbo.Hierachical_View_with_Jobnumbers as ser_number_all
where not exists (select 1
from Hierachical_View_with_Jobnumbers as hv
where hv. Serialnumber = ser_number_all.Serialnumber
and hv. TypeName = ser_number_all.TypeName
and hv. Date = ser_number_all.Date
and hv. Parent_Serialnumber = ser_number_all.Parent_Serialnumber
and hv. JobNumber = ser_number_all.JobNumber
and hv. ProductNode = ser_number_all.ProductNode);
只要查看還沒有任何新的記錄,它看起來不錯,我沒有得到任何錯誤,輸出爲0記錄,因爲它應該是。
當我添加一個新的記錄源表和視圖有1分以上的記錄,我總是收到此錯誤:
Msg 2627, Level 14, State 1, Line 4
Violation of PRIMARY KEY constraint 'PK__ser_numb__F2753A12C4ABA976'. Cannot insert duplicate key in object 'dbo.ser_number_all'. The duplicate key value is (.x3666AB05).
The statement has been terminated.
我不明白爲什麼它會插入一個重複的值在主鍵列中,因爲在我的WHERE子句中我看不到任何錯誤。
我也嘗試過使用IS NULL而不是= ser_number_all.TypeName和所有其他列可以有一個NULL值,但仍然是相同的。
同樣,我來自甲骨文,看起來我必須學習MS SQL與Oracle相比的多種多樣性。
欣賞任何建議:-) THX
編輯:
這裏查看的代碼:
CREATE VIEW [dbo].[Hierachical_View_with_Jobnumbers]
AS
WITH ProductList
AS
(
SELECT p.Serialnumber,
p.Type_Id,
p.Parent_Serialnumber,
p.ActiveJob_Jobnumber as JobNumber,
N'/' + CONVERT(NVARCHAR(4000), ROW_NUMBER() OVER (ORDER BY p.Serialnumber)) + N'/' AS ProductNode_AsChar
FROM Products AS p
WHERE p.Parent_Serialnumber IS NULL
UNION ALL
SELECT p.Serialnumber,
p.Type_Id,
p.Parent_Serialnumber,
JobNumber,
pl.ProductNode_AsChar + CONVERT(NVARCHAR(4000), ROW_NUMBER() OVER (ORDER BY p.Serialnumber)) + N'/'
FROM Products AS p
INNER JOIN ProductList AS pl ON p.Parent_Serialnumber = pl.Serialnumber
)
SELECT Serialnumber,
pt.Name as TypeName,
Parent_Serialnumber,
JobNumber,
CONVERT(HIERARCHYID, ProductNode_AsChar) AS ProductNode
FROM ProductList as pl
INNER JOIN ProductTypes as pt on pl.Type_Id = pt.Id;
要插入的'[DBO] [ser_number_all]'你是關聯'Hierachical_View_with_Jobnumbers' – TheGameiswar
是的,Hierachical_View_with_Jobnumbers是我們獲取數據的視圖,所有新記錄應該插入到表ser_number_all中。 – wayne7215
我在說什麼是嘗試與視圖關聯 – TheGameiswar