我正在写一个c#.net应用程序并需要以下帮助。
我有4张桌子:
用户(姓名,...,UsrID)
产品(名称,产品)
评级(评级,RatID)
ProdRatings(UsrID,ProdID,RatID,DateRated,RatedBy)
现在我有一张包含以上表格的excel表格:
Sheet1:UserName,ProductName,Rating,DateRated)
我需要在用户及其产品和评级中填写此电子表格,并将其全部插入到sql db中。
现在我可以导入单个表没问题,但是很难一次性导入到所有4个。
非常感谢任何帮助。
答案 0 :(得分:0)
假设您使用sql server:
insert into users (name)
SELECT distinct a.UserName
FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=C:\test\xltest.xls', [Sheet1$]) a
where not exists (select null from Users where Name = a.UserName)
insert into Products (Name)
SELECT distinct a.ProductName
FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=C:\test\xltest.xls', [Sheet1$]) a
where not exists (select null from Products where Name = a.ProductName)
insert into Ratings (Rating)
SELECT distinct a.Rating
FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=C:\test\xltest.xls', [Sheet1$]) a
where not exists (select null from Ratings where Name = a.Rating)
insert into ProdRatings (UsrID, ProdID, RatID, DateRated)
SELECT Users.UsrID, Products.ProdID, Ratings.RatID, a.DateRated
FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=C:\test\xltest.xls', [Sheet1$]) a
inner join Users
on a.UserName = Users.Name
inner join Products
on a.ProductName = Products.Name
inner join Ratings
on a.Rating = Ratings.Rating
left join ProdRatings
on Users.UsrID = ProdRatings.UsrID
and Products.ProdID = ProdRatings.ProdID
and Ratings.RatID = ProdRatings.RatID
where ProdRatings.ID is null
首先导入新用户,产品和评级,然后再导入ProdRatings。
如果您不使用sql server,请先以标准方式将Excel文件导入临时表,然后再进行部分插入。我希望这符合你的需求。