Some sample data:
DECLARE @TARGET TABLE ( ID INT, value INT ) ;
DECLARE @SOURCE TABLE ( ID INT, value INT )
INSERT INTO @TARGET VALUES ( 1, 213 )
INSERT INTO @TARGET VALUES ( 2, 3 )
INSERT INTO @TARGET VALUES ( 3, 310 )
INSERT INTO @TARGET VALUES ( 4, 43 )
INSERT INTO @SOURCE VALUES ( 1, 134 )
INSERT INTO @SOURCE VALUES ( 2, 34 )
INSERT INTO @SOURCE VALUES ( 13, 310 )
INSERT INTO @SOURCE VALUES ( 14, 43 )
INSERT INTO @SOURCE VALUES ( 15,32 )
INSERT INTO @SOURCE VALUES ( 16, 30 )
INSERT INTO @SOURCE VALUES ( 17, 60 )
INSERT INTO @SOURCE VALUES ( 18, 5 )
MERGE @TARGET t USING (SELECT * FROM @SOURCE) AS s ON (t.id = s.id)
WHEN NOT MATCHED THEN
INSERT VALUES (s.id,s.value);
SELECT * FROM @TARGET
So I'm having a target table , and a source table. What I want to accomplish is that when there is a large number of not matched
items, to only insert the x top items with the highest value.
Using top on the merge itself won't work, because that would limit the whole source table, I want to do something like
WHEN NOT MATCHED
LIMIT(5) AND ORDER BY Value DESC --only insert the 5 non-matches with the highest value
INSERT VALUES (s.id,s.value)
---- UPDATE ----
My MERGE statement also contains an WHEN MATCHED THEN statement:
WHEN MATCHED THEN
UPDATE SET t.value = s.value
this sadly negates the answers given by Ian and Dog...