DECLARE @NewSessionIDTable TABLE (NewSessionID UNIQUEIDENTIFIER)
INSERT INTO TrainingSession
(
TrainingID
,TrainingSessionStatusID
,TrainingSessionDesc
,TrainingSessionDate
,TrainingSessionTime
,TrainingSessionDuration
,TrainingSessionLocation
,TrainingSessionTrainer
,TrainingSessionNotes
,LastModified
,RevisionNum
)
OUTPUT INSERTED.TrainingSessionID INTO @NewSessionIDTable
SELECT
training.TrainingID
, 0
, '2017 Training'
, null
, null
, null
, 'Online'
, null
, null
, GETDATE()
, 1
FROM TrainingSession, dbo.AnnualData illumivuData
WHERE training.TrainingTypeID = 26
AND illumivuData.Status = 'Users Not Started'
AND illumivuData.DepartmentIDTEXT IN ( SELECT DepartmentID from Training.Department)
AND illumivuData.FirmEmployeeIDTEXT IN (SELECT EmployeeID from Training.Employees)
INSERT INTO
-- Another Table the outputted GUID that was generated above.
我需要将数据插入到两个表中,插入第二个表依赖于在将新行插入第一个表后生成的GUID。
我已经成功完成了第一部分,因为e.NewPk是由早期插入语句(保存在表变量中)生成的主键。我现在遇到的问题是,当执行第二个insert语句时,我收到了违反主键约束错误的情况。
为了检查插件是否实际上没有返回重复项,我将这个完全相同的insert语句运行到临时表中。没有重复。
但是当我与之前的insert语句一起运行时,我收到错误。
知道该怎么做?我当然认为我接近了这个错误。
答案 0 :(得分:2)
首先将“联接”更改为:
FROM ComplianceTraining.Training a
INNER JOIN dbo.AnnualOnline2017Data b
ON ??? scalar ???
INNER JOIN ComplianceTraining.EdsDepartment c
ON c.DepartmentID = b.DepartmentIDTEXT
INNER JOIN ComplianceTraining.EdsGeneralEmployee d
ON d.EdsGeneralEmployee = b.FirmEmployeeIDTEXT
INNER JOIN @NewPKTable e
ON ???
WHERE
a.TrainingTypeID = 26
AND b.Status = 'Users Not Started'
答案 1 :(得分:0)
此问题的解决方案是预先声明临时表,其中包含所需的所有信息,只需生成带有NEWID()的GUID,而不是允许表自行生成它们。
CREATE TABLE customer_order (
id_customer_order INT AUTO_INCREMENT NOT NULL,
id_employee INT NOT NULL,
id_payment INT NOT NULL,
total DECIMAL(10,2) NOT NULL,
status NUMERIC(11) NOT NULL,
created_at TIMESTAMP NOT NULL,
updated_at TIMESTAMP NOT NULL,
PRIMARY KEY (id_customer_order)
);
CREATE TABLE customer_order_line (
id_order_line INT AUTO_INCREMENT NOT NULL,
id_customer_order INT NOT NULL,
id_products INT NOT NULL,
cost_without_taxes DECIMAL(10,2) NOT NULL,
cost_with_taxes DECIMAL(10,2) NOT NULL,
final_price DECIMAL(10,2) NOT NULL,
quantity NUMERIC(11) NOT NULL,
total_without_taxes DECIMAL(10,2) NOT NULL,
total_with_taxes DECIMAL(10,2) NOT NULL,
total DECIMAL(10,2) NOT NULL,
status NUMERIC(11) NOT NULL,
PRIMARY KEY (id_order_line)
);
这就是它的样子,除了在最初的选择之后还有更多的联合选择。
在此之后,我继续直接从这个TempTable向TrainingSession和TrainingEmployee插入数据。