2012-08-22 32 views
1

我需要插入的東西負載到我的數據庫我可以插入基於在SQL Server查詢

寫出多行手寫的查詢會是這樣的(但有更多的東西!)

Insert into MyTable (country_id, event) values (1001, 'up') 
Insert into MyTable (country_id, event) values (1001, 'down') 
Insert into MyTable (country_id, event) values (1002, 'up') 
Insert into MyTable (country_id, event) values (1003, 'down') 
.... 
Insert into MyTable (country_id, event) values (9999, 'up') 
Insert into MyTable (country_id, event) values (9999, 'down') 

我可以寫一些神奇的SQL加入/合併奇蹟查詢,將獲得所有的country_ids和所有'事件'類型,並創建我需要的數百個插入語句?

編輯:
有一個國家的表。應該插入到MyTable中的是SQL查詢的結果,並且該查詢的每個結果都需要MyTable中的「上」和「下」行。我不想手工編制查詢就足夠了。

在實際情況中,「上」和「下」多於但可以手動輸入或作爲進一步查詢的結果。

+0

要插入的表或在文本文件中的數據? –

+1

你真的想要生成這些數據嗎?你有「國家」和「事件」數據表嗎? –

回答

7

創建笛卡爾積的國家和事件列表,並立即插入它們:

insert into MyTable (country_id, event) 
select countries.country_id, 
     e.[event] 
    from countries 
cross join 
(
    select 'Up' [event] 
    union all 
    select 'Down' 
) e 
2

可以跳過

Insert into MyTable (country_id, event) values 

Insert into MyTable (country_id, event) values (1001, 'down'), 
(1002, 'up'), 
(1003, 'down') 

更換或者你可以看看BULK INSERTbcp如果你的數據是從一個文件來。

或者,如果你知道什麼國家和事件,

Insert MyTable (country_id, event) 
SELECT countryid, event 
FROM country, events 

會把所有組合到表

2

您可以加入VALUES這樣的:

INSERT INTO MyTable (country_id, event) 
VALUES (1001, 'up'),(1001, 'down'),(1002, 'up'),(1003, 'down') 
+0

我仍然需要手工創建括號中的巨大列表,並且在500個左右後會感到困惑和憤怒! – Loofer