规范化 table 并将 nvarchar 列转换为外键引用的最佳实践

Best practices for normalizing a table and converting a nvarchar column to a foreign key reference

我在 T-SQL 中有一个大的、未规范化的 table。假设它具有以下结构:

tbl_Item:
ItemID
ItemName
ItemGroup
Price

有了这样的数据:

1 - ItemA - GroupA - .99
2 - ItemB - GroupA - .99
3 - ItemC - GroupA - .99
4 - ItemX - GroupB - .00
5 - ItemY - GroupB - .00

我想把它标准化成两个,全新的 tables:

tbl_Item:
ItemID
ItemName
FK_Group

和:

tbl_Group:
GroupID
GroupName
Price

我遇到的问题是从初始 table 获取 ItemGroup 数据并将其替换为新 table 的相应 GroupID。我将通过 运行:

填充 tbl_Group table
SELECT DISTINCT ItemGroup FROM tbl_Item

...并将所有值插入 tbl_Group,从而为它们提供 ID 号。

那时我能看到的唯一方法是编写一个循环遍历 tbl_Item 的脚本,针对新的 tbl_Group table 查询 ItemGroup 列,并将 ID 插入到新项目 table 的 FK_Group 列。

有更好的方法吗?

您可以将 table 创建为:

select identity() as GroupId, GroupName, Price 
into tbl_groups
from tbl_item
group by GroupName, Price;

或者,将 table 创建为:

create table tbl_groups (
    GroupId int identity() primary key,
    GroupName varchar(255),
    Price number(10, 2)
);

insert into tbl_groups(GroupName, Price)
    select distinct GroupName, Price
    from tbl_Items;