我有一个用户可以添加新[应用程序]的场景。此[应用程序]可以包含许多[变体]。 a [Variation]可以有多个[VariationLines]
例如,这里有一些数据需要澄清:
Project
ProjectID Name
1 Test Project
Application
ApplicationID ProjectID ApplicationValue
1 1 £500
Variation
VariationID ApplicationID VariationTotalAmount
1 1 £100
2 1 £250
VariationLine
VariationLineID VariationID PreviousPercentage VariationValue VariationPercentage ApplicationID
1 1 0% £50.00 50% 1
2 2 0% £62.50 25% 1
问题
当用户添加应用程序[ApplicationID:2]时,我希望SQL Server复制与[ApplicationID:1]关联的ROWS ..
因此,使用上面的示例数据,我如何复制[VariationLineID:1] AND [VariationLineID:2],并指定如果新应用程序[应用程序:2]上存在它不需要复制它们再次?
此查询选择要复制的行但我不明白如何阻止它们再次复制所以有人可以指出我正确的方向来防止这种情况吗?
INSERT INTO VariationLine
(variationid,
applicationid,
applicationcounter,
variationpercentage,
variationvalue,
previouspercentage,
projectid,
totalvariationvalue,
variationretention)
SELECT VariationLine.variationid,
ApplicationID = (2),
ApplicationCounter = (2),
VariationPercentage = variationpercentage,
VariationValue = 0,
PreviousPercentage = variationpercentage,
ProjectReference = projectreference,
TotalVariationValue = totalvariationvalue,
VariationRetention = 0
FROM variationsincluded
WHERE projectid = (1)
AND applicationcounter = (2) - 1
AND EXISTS (SELECT *
FROM applications
WHERE VariationLine.applicationid !=
applications.applicationid)
上面的CODE将选择正确的结果,运行一次后VariationLineID:3和VariationLineID:4被INSERTED ..现在如果我再次运行它然后它会再次插入相同的数据,我只想要这个被插入ONCE
以上是上述查询运行后的期望结果:
Application
ApplicationID ProjectID ApplicationValue
2 1 £500
VariationLine
VariationLineID VariationID PreviousPercentage VariationValue VariationPercentage
1 1 0% £50.00 50%
2 2 0% £62.50 25%
3 1 50% £0.00 50%
4 2 25% £0.00 25%
所以要解释一下,Query会复制VariationLineID 1和2,并根据ApplicationID的FOREIGN KEY关系将它们重新插入到同一个表中。 VariationLineID 3的PreviousPrecentage和VariationPercentage将取自VariationLineID 1,依此类推...这使用户能够修改为第二应用程序的VariationLine而不影响应用程序1