Skip to content
Advertisement

How to set unique column values using an update from select statement

I am trying to achieve a 1:1 mapping between two tables based on their content. Unfortunately, the 1:1 mapping can not be perfect, as not both tables contain the exact same set of data. Anyways, I want to have the best possible match.

Let the code talk in an example:

My expected output would be something like this:

However, what I get is:

Well, as mentioned in the comment above the last code line: My problem is, that the update ignores previously updated rows and thus inserts a single Nodes.ID multiple times. However, I want the Links.NodeID column to be unique after this step. (Not unique in general but for this step)

Any Ideas on how to achieve that? I am thankful for any tip or idea, as I am failing on this for days now.

Thanks a lot, DonLuigi

Advertisement

Answer

Use ROW_NUMBER() window function in each of the tables so you can link correctly the rows that you want to update:

See the demo.

Or with a CTE:

See the demo.
Results:

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement