2016-09-16 99 views
0

在一个假设的例子中关系表,说我有两个表:FARM水果更新使用合并

农场组织,如:

FARM_ID Size  
1   50  
2   100 
3   200 
... 

和水果的组织,如:

Reference_ID FRUIT 
1    Banana 
1    Grape 
1    Orange 
2    Banana 
2    Strawberry 

FRUIT表从采取从Excel参数@fruit其是分隔小号创建使用'/'。

例如,@fruit = '香蕉/葡萄/橙'

而使用如下语句:

INSERT INTO FRUIT(
Fruit, 
Reference_ID, 
) 

SELECT Fruit, Scope_IDENTITY() from split_string(@fruit, '/') 

凡split_string是一个函数。

我的目标是检查更新。我想收入一个Farm_ID和@fruit,并检查是否有任何变化已经对水果。

1)如果值没有改变,不做任何事情

2)如果添加了新的水果,它与farm_ID

3)添加到水果表如果有果在FRUIT表中,不符合尊重FARM_ID的新分隔列表,请将其从FRUIT表中删除。

我认为合并声明可能会奏效,但可以接受建议。如果有什么不清楚,请告诉我。谢谢

编辑

林相当新的SQL,但使用的合并已经尝试...

Declare @foo tinyint 
Merge Fruit as Target 
Using (Select Fruit , @workingID From split_string(@fruit, '/') As source  (fruit, ID) 
[email protected] is just a way to get the ID from other parts of the sproc. 
ON (TARGET.fruit = source.fruit) 
WHEN MATCHED THEN 
SET @foo = 1 
WHEN NOT MATCHED 
THEN DELETE 
WHEN NOT MATCHED THEN 
INSERT INTO FRUIT(
Reference_ID, 
Fruit 
) 
VALUES(

然后我停留在如何让独特的,新的价值观

+0

@ajeh,看到编辑。希望可以帮助 – user3697498

回答

0

位任何方式您的输入包含农场ID的新水果列表。所以更好的选择是删除现有的并将新的水果列表插入农场。

示例脚本如下。

--loading the input to temp table 
    SELECT Fruit,@referenceid ReferenceId -- farmid corresponding tithe fruit list 
     INTO #temp 
    FROM Split_string(@fruit,'/') 

    -- delete the existing data against the given farmid 
    DELETE FROM fruit f 
    WHERE EXISTS (SELECT 1 FROM #temp t 
     WHERE f.Reference_id=t.ReferenceId) 

    -- insert the new list 
    INSERT INTO fruit 
    SELECT fruit,referenceId 
    FROM #temp 
+0

这会更好,那么使用合并时匹配,当不匹配的源,当不匹配的目标? – user3697498