开发者

Capturing a relation between two rows while one of the two rows being inserted

Please be patient while I explain my scenario. I have following two tables:

Items(id, plan, free)

-- ‘id’ is identity column.

ItemsIncludes(MasterId, IncludeId)

There are two types of items – purchased and free (included). Regardless, both types of items are stored in Items table (obviously the bit field ‘free’ is set according to the type). The ItemsIncludes table establishes a one-to-many relationship between a purchased item (MasterId) and items included as free with it (IncludeId).

Step 1 is to insert purchased items from cart (no problem).

Step 2 Is to insert free items for each purchased item inserted based on purchased item’s plan (which has nothing to do with the problem being faced).

Step 3 is to insert the IDs generated during this first 2 steps in their proper relationship into the ItemsIncludes table (problem).

The requirement is to capture free itemId being generated during insertion along with its purchased itemId. The output clause would have done this, if following was legal:

Step 2--

Declare @ItemsIncludesIntermediate table(MasterId int, IncludeId int)
Insert into Items
(PlanId, IsFree)
Output it.ID -- Illegal
, inserted.ID into @ItemsIncludesIntermediate
Select pli.IncludePlanId, 1
From Items it
Join PlansIncludes pli on it.PlanId = pli.MasterPlanId

The plan structure is also similar but is not relevant to the problem at hand therefore not described.

SQL Server doesn’t allow other than inserted.columns to be referred in output clause during insert; however, it is not the same in case of updates/delete, in which statements, referring to any identifier participating in FROM 开发者_开发技巧list is allowed. E.G.:

Note: I’ve not run the following example, but it is legal.

Delete Items
Output iti.MasterID, deleted.ID into @ItemsIncludesIntermediate
From items it
Join ItemsIncludes iti on it.ID = iti.IncludeId

In short, if I cannot do this with output clause, then how can I capture free itemId as it is being generated along with the purchased itemId for which it’s being generated?

I’m open for view and instead of trigger approach, if it is possible with that. The fundamental thing is that I don’t want to change the structure. E.G. I don’t want to remove ItemsIncludes table and have MasterItemId be included into Items table.

The problem looked simple at first, but now getting on my nerves


If you use SQL Server 2008 you can use merge instead of insert and get the mapping between the ID's.

Have a look at this question for more details on how to do it.

Using merge..output to get mapping between source.id and target.id

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜