T-SQL - 从非规范化数据创建新的外键关系
我正在尝试找出最佳的 Transact-SQLTransact-SQL,将非关系表转换为关系性更强且支持外键的表。
假设我有一个表 FRUIT,
Id Name USState
1 Apple Washington
2 Pineapple Hawaii
3 Orange Florida
4 Peach Georgia
etc
我希望各州成为自己的表,并具有 Id 和名称:
INSERT INTO USSTATE (Name) Select DISTINCT USState from FRUIT
现在我有表 USSTATE
Id Name
1 Alabama
2 Alaska
etc.
现在如何更新表 FRUIT 中的 USState 值以递归地指向 USSTATE 的 Id?
我可以逐个州
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!!!
等
进行,但我想递归地进行。感谢您的帮助?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
并非每个数据库都支持 UPDATE 语法中的 JOIN - 相关子查询是最可移植的方法:
请注意 将
FRUIT.usstate
列的数据类型从 VARCHAR/etc 更新为 INT:Not every database supports JOINs in the UPDATE syntax - the correlated subquery is the most portable approach:
Mind that you update the data type for the
FRUIT.usstate
column from VARCHAR/etc to INT:我对上面的答案投了赞成票,因为给出了 T-SQL
但是,您的示例数据将一种水果与一种状态联系起来......因此您将创建一对一的关系。
与您的问题相反,您的数据已经标准化(除非表中存在您未包含的重复或多个水果)
I voted up the answer above mine for giving the T-SQL
However, your example data ties one fruit to one state... so you'd be creating a one-to-one relationship.
In contrast to your question, your data is already normalized (unless there is duplicated or multiple fruit in the table which you didn't include)
您想要一个带有表 USState 外键的新列,对吗?
首先为表 FRUIT 创建新列(将其称为“USStateId”)。您必须暂时将该列设置为空。
然后在USState.Id和Fruit.USStateId之间创建FK关系。
然后编写一个查询以使用正确的值更新新列:
接下来,使您添加的新列不可为空。
最后,从 Fruit 表中删除 USState 列。
You want a new column with a foreign key to table USState, is that correct?
Start by creating the new column to table FRUIT (call it "USStateId"). You will have to make the column nullable temporarily.
Then create an FK relationship beteen USState.Id and Fruit.USStateId.
Then write a query to update the new column with the correct values:
Next, make the new column you added non-nullable.
Finally, remove the USState column from the Fruit table.