2016-09-16 97 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