Pregunta

I have a table called States with an ID and a name of the state (Indiana). I need to create a table with adjoining states to each state by trying to use the same table. I running into circular references every time I do it. This is with SQL Server. I want cascading involved for deletes and updates.

STATES
Id
State

This is what I want, but I keep getting the circular reference error. I need to combine two IDs from the states table somehow, thoughts?

STATES           ADJOININGSTATESTATE        ADJOININGSTATE
                 Id
Id       ->      StateId              ->    StateId
State            AdjoiningStateId     ->    Id
¿Fue útil?

Solución

SQL Server won't let you cascade like this, you'll need to use triggers. Here's an example of how to do deletes. Updates are left as an exercise to the reader if you really decide you need them.

Create Table AdjoiningStates (
    State1ID int not null constraint FK_AdjoiningStates_States1 Foreign Key References States,
    State2ID int not null constraint FK_AdjoiningStates_States2 Foreign Key References States,
    Constraint PK_AdjoiningStates Primary Key (State1ID, State2ID)
)
Go
Create Trigger States_Delete On States Instead Of Delete As
    Delete AdjoiningStates From AdjoiningStates a inner join deleted d on a.State1ID = d.StateID
    Delete AdjoiningStates From AdjoiningStates a inner join deleted d on a.State2ID = d.StateID
    Delete States From States s inner join deleted d on s.StateID = d.StateID
Go

On certain versions of SQL, if this is going to be a bottleneck, it's more efficient to copy the deleted table into a temporary table before using it multiple times.

Example Fiddle

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top