我如何将数据批量加载到外键引用的 SQL 服务器 table 但数据是 Excel 格式的普通数据?

How would I bulk load the data into a SQL Server table which is referenced by the foreign keys but the data is plain in Excel format?

我有一个 table BasicDetails 包含这些列:

ID   Name   Father    Country_ID   City_ID   ContactDetails_ID

但客户已与我共享 Excel sheet,我应该将其加载到 table。 sheet 有以下列

ID   Name   Father   CountryName   CountryCode   CityName   CityCode   ContactNo   CellNo   Address

现在,在我的数据库 CountryName, CountryCode, CityName 中,这些存储在一个单独的 table 中,名为 Countries

CityName CityCode 保存在单独的 table Cities.

ContactNo CellNo Address 存储在单独的 table ContactDetails

它们各自的主键在主table.

中用作外键

现在的问题是我 sheets 有几千条记录,我不知道如何将数据导入到 BasicDetails table 中,它被国外引用键。

您需要分多个部分执行此操作。

将 Excel table 加载到分段 table 中,比如 staging

然后,确保外键引用有效,例如:

select s.countrycode, count(*)
from staging s left join
     countries c
     on s.countrycode = c.countrycode
where c.countrycode is null
group by s.countrycode;

您需要为 citiescontacts 重复此操作。后者可能更复杂。此问题不会询问如何处理相互冲突的信息——如果您需要这方面的帮助,请提出一个新问题。

当您确信所有参考 table 都正确时,您可以使用 join 加载 table:

insert into basicdata (Name, Father, Country_ID, City_ID ContactDetails_ID)
    select s.name, s.father, co.country_id, ci.city_id,
           con.contact_id
    from staging s join
         counties co
         on s.countrycode = co.countrycode join
         cities ci
         on s.citycode = ci.citycode join
         contacts con
         on s.contacctno = con.contactno;