2011-11-27 37 views
5

場景如何通過查找值將記錄插入SQL?

我需要通過電子表格(唯一可用的選項)每天更新SQL 2008數據庫。這種格式非常基本,但是可能有數百萬條記錄。 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 

DB設置

我的數據庫設置了三個獨立的表:

//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以插入與查找表中的信息匹配的記錄?我怎樣才能從這個去:

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 
+0

您打算如何將電子表格數據導入sql-server? –

回答

5

你可以嘗試這樣的事:

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

沒有任何容錯,但只要你能解析您的電子表格值到SELECT語句它會工作。

+0

謝謝!這個技巧簡單而又甜美。 – Paul

2

其插入到表數據的源被定義爲

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

因此,我們可以使用,其定義爲

derived_table一個derived_table

是否返回任何有效的SELECT語句s行數據 被加載到表中。 SELECT語句不能包含公用表表達式(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 

這將允許您刪除您當前正在考慮的循環。

+0

這比BryceAtNetwork23的答案更好,這對我來說似乎更簡單? (儘管兩個答案都有效) – Paul

+0

如果您要一次處理一條記錄,它們是一樣的。如果您使用臨時表或OPENDATASOURCE一次處理它們,那麼您必須使用derived_table –

+0

瞭解,並感謝您的幫助。不幸的是,你的方法不適用於我。 – Paul