I am trying to figure out the best Transact-SQL to transform non-relational tables into tables that are more relational, and support foreign keys.
Suppose I have a table FRUIT
Id Name USState
1 Apple Washington
2 Pineapple Hawaii
3 Orange Florida
4 Peach Georgia
etc
I want the States to be their own table with an Id and Name :
INSERT INTO USSTATE (Name) Select DISTINCT USState from FRUIT
Now I have table USSTATE
Id Name
1 Alabama
2 Alaska
etc.
How do I now update the USState value in table FRUIT to point to the Id of USSTATE recursively?
I can do it State by State
DECLARE @USSTATE nvarchar(100)
Set @USSTATE = 'Alabama'
Update FRUIT Set USState = (SELECT Id from USSTATE where Name like @USSTATE)
Set @USSTATE = 'Alaska' -- do this for each State? Arghh!!!
etc etc.
, but I want to do it recursively. Thanks for any help?