2

I have two main tables

  1. Postion
  2. geography

If the row in position intersects the row in geography, I need to insert it in third table.

But the problem is I have to check the existing row in the third table and then insert it.

I can do this with set operations,but the problem is I can't process each row (i.e. if there are two rows with similar data,need to insert only the first).

I can do with cursor but I read its a bad thing.

Can anyone help me to process each row before inserting?

1
  • You should use a merge statement with a proper ON clause to insert data into your third table. Commented Aug 22, 2016 at 9:25

2 Answers 2

3

At first put all you need in CTE with ROW_NUMBER to get only 1 row for each ID. Then MERGE:

;WITH cte AS (
SELECT  g.*,
        ROW_NUMBER() OVER (PARTTION BY SomeColumn ORDER BY SomeColumn) as rn
FROM Postion p
INNER JOIN geography g
    ON p.someID = g.SomeID
)

MERGE ThirdTable as target
USING (SELECT * FROM cte WHERE rn = 1) as source
ON target.SomeID = source.SomeID
WHEN NOT MATCHED THEN 
    INSERT (target fields)
    VALUES (source values);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your help,the solution was nice,I tried using it but it was not fitting my use case.Also I needed to insert on match as well.I ended up using cursor.
0

// #temp contains all the required field from intersection of position and geography and will check it with third table using left join

select p.* into #temp
from position p inner join geography g
on p.id = g.id


insert into thirdtable
select * from #temp t1 left join thirdtable t2
on t1.id = t2.id
where t2.id is null

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.