我有几个相关的表,我希望能够在更新引用时复制某些行.
我想复制Table1中的一行,以及Table2和Table3中所有相关的行,我试图找出一种有效的方法来完成迭代行.
例如,我有一张篮子桌子:
+----------+---------------+
| BasketId | BasketName |
+----------+---------------+
| 1 | Home Basket |
| 2 | Office Basket |
+----------+---------------+
每个篮子都有水果:
+---------+----------+-----------+
| FruitId | BasketId | FruitName |
+---------+----------+-----------+
| 1 | 1 | Apple |
| 2 | 1 | Orange |
| 3 | 2 | Mango |
| 4 | 2 | Pear |
+---------+----------+-----------+
每种水果都有一些特性:
+------------+---------+--------------+
| PropertyId | FruitId | PropertyText |
+------------+---------+--------------+
| 1 | 2 | Is juicy |
| 2 | 2 | Hard to peel |
| 3 | 1 | Is red |
+------------+---------+--------------+
对于此示例,我的属性特定于单个水果行,这些“apple”属性不是所有篮子中所有苹果的属性,仅适用于该特定篮子中的特定苹果.
我想要做的是复制一个篮子.所以给了篮子1,我想创建一个新的篮子,复制它包含的果实行,并复制指向那些果实的属性.最后我希望有这样的数据:
+----------+---------------+
| BasketId | BasketName |
+----------+---------------+
| 1 | Home Basket |
| 2 | Office Basket |
| 3 | Friends Basket|
+----------+---------------+
+---------+----------+-----------+
| FruitId | BasketId | FruitName |
+---------+----------+-----------+
| 1 | 1 | Apple |
| 2 | 1 | Orange |
| 3 | 2 | Mango |
| 4 | 2 | Pear |
| 5 | 3 | Apple |
| 6 | 3 | Orange |
+---------+----------+-----------+
+------------+---------+--------------+
| PropertyId | FruitId | PropertyText |
+------------+---------+--------------+
| 1 | 2 | Is juicy |
| 2 | 2 | Hard to peel |
| 3 | 1 | Is red |
| 4 | 6 | Is juicy |
| 5 | 6 | Hard to peel |
| 6 | 5 | Is red |
+------------+---------+--------------+
复制篮子和它的果实非常简单,但重复水果的属性似乎导致迭代行,我希望在TSQL中有更好的解决方案.
有任何想法吗?
最佳答案 为什么不加入FruitName来获得新旧FruitId的表格?考虑信息将同时添加….它可能不是最好的选择,但你不会使用任何周期.
INSERT INTO BASKET(BASKETNAME)
VALUES ('COPY BASKET')
DECLARE @iBasketId int
SET @iBasketId = @@SCOPE_IDENTITY;
insert into Fruit (BasketId, FruitName)
select @iBasketId, FruitName
from Fruit
where BasketId = @originalBasket
declare @tabFruit table (originalFruitId int, newFruitId int)
insert into @tabFruit (originalFruitId, newFruitId)
select o.FruitId, n.FruitId
from (SELECT FruitId, FruitName from Fruit where BasketId = @originalBasket) as o
join (SELECT FruitId, FruitName from Fruit where BasketId = @newBasket) as n
on o.FruitName = n.FruitName
insert into Property (FruitId, PropertyText)
select NewFruitId, PropertyText
from Fruit f join @tabFruit t on t.originalFruitId = f.FruitId