Note that there are some explanatory texts on larger screens.

plurals
  1. POUpgrading a Column to a Foreign Key When It Already Has Data In It
    primarykey
    data
    text
    <p>I'm working with a database in SQL Server Management Studio and I have two tables, Route and Tractor (this is a simplified example). Currently, the Route table contains a column called TractorID. It isn't a foreign key or index of the Tractor table's ID column, but it is used in our application to search the Tractor table by their ID. This has allowed our users to delete tractors in the past without affecting any routes that tractor was used on.</p> <p>I'm now upgrading the database so that the TractorID column is a foreign key to the Tractor table's ID column, but I've come across a problem. Since users have been deleting tractors and this isn't updated in the route table, there are a few routes with TractorIDs that are not present in the Tractor table anymore. I need these false IDs to be set to null beforehand so that I can upgrade the column to a foreign key.</p> <p>I've done so using the statement below:</p> <pre><code>UPDATE Route SET Route.TractorID = NULL WHERE Route.TractorID IS NOT NULL AND NOT EXISTS(SELECT * FROM Tractor WHERE Tractor.ID = Route.TractorID) </code></pre> <p>So far, this statement seems to do the trick, but I'm worried about how efficient it is. We have a few databases that contain 2.5 million or so routes a month that need to be upgraded. I think this subquery triggers for each line, and so I'm hoping to find a solution that may involve joining the route and tractor tables together (<code>JOIN Tractor ON Route.TractorID = Tractor.ID</code>) and then setting the <code>TractorID</code> to <code>NULL</code> if a join for that row was unsuccessful (i.e. the <code>TractorID</code> didn't match any <code>Tractor.ID</code>s).</p> <p>Would this be possible? Or is my current solution good enough? Thanks in advance.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload