如何插入logging到SQL查找值?

脚本

我需要通过电子表格每日更新SQL 2008数据库(唯一可用的选项)。 格式是非常基本的,但是可能有数百万条logging。 Column1和Column3将有许多预定义的重复值,已经拉出到单独的表。

电子表格样本

Column1 Column2 Column3 Apple 10 Red Apple 20 Red Apple 15 Blue Apple 21 Green Orange 10 Orange Orange 7 Orange Orange 9 Red Orange 70 Blue Orange 10 Blue 

数据库设置

我的数据库设置了三个独立的表格:

 //Lookup_Column1 id type 1 Apple 2 Orange //Lookup_Column3 id type 1 Red 2 Blue 3 Green 4 Orange //Main - this is what should be inserted, after Column1 //and Column2 are matched to their respective ID's key Column1 Column2 Column3 1 1 10 1 2 1 20 1 3 1 15 2 4 1 21 3 5 2 10 4 6 2 7 4 7 2 9 1 8 2 70 2 9 2 10 2 

我如何编写SQL来插入匹配查找表信息的logging? 我怎样才能做到这一点:

 INSERT INTO Main(Column1, Column2) VALUES ('Apple', 10, 'Red'); 

对此:

 INSERT INTO Main(Column1, Column2) VALUES (1, 10, 1); //pulled from lookup tables, where Apple = 1 and Red = 1 

你可以尝试这样的事情:

  INSERT INTO Main(Column1, Column2, Column3) VALUES ( (SELECT id FROM Lookup_Column1 WHERE type = 'Apple'), 10, (SELECT id FROM Lookup_Column3 WHERE type = 'Red') ); 

没有任何容错,但是只要你能够将你的电子表格值parsing成SELECT语句就可以工作。

插入到表中的数据源被定义为

  VALUES ( { DEFAULT | NULL | expression } [ ,...n ] ) [ ,...n ] | derived_table | execute_statement | <dml_table_source> | DEFAULT VALUES 

所以我们可以使用被定义为的derived_table

derived_table

是否有有效的SELECT语句返回要加载到表中的数据行。 SELECT语句不能包含公用表expression式(CTE)。

  INSERT INTO MAIN (Column1, Column2, column3) SELECT lc1.id, 10, lc2.id FROM Lookup_Column1 lc1, Lookup_Column2 lc2 WHERE lc1.type = 'Apple' and lc2.type = 'Red' 

有关更多信息,请参见INSERT(Transact-SQL)

如果您可以将电子表格值存入临时表(或直接使用链接的服务器或OPENDATASOURCE链接到电子表格),则可以将INSERT子句更改为

  INSERT INTO MAIN ( Column1, Column2, column3) SELECT lc1.id, s.column2, lc2.id FROM OPENDATASOURCE('Microsoft.Jet.OLEDB.4.0', 'Data Source=C:\YourdataSource.xls;Extended Properties=EXCEL 5.0')...[Sheet1$] s INNER JOIN Lookup_Column1 lc1 ON s.column1 = lc1.type INNER JOIN Lookup_Column2 lc2 ON s.column3 = lc2.type 

这将允许您删除您当前正在考虑的循环。

你有没有尝试过使用SELECT INTO语句? 这使您可以从一个表中select数据并将其插入到另一个表中。

http://www.w3schools.com/sql/sql_select_into.asp