2014-02-17 37 views
0

一個查詢插入多行我的userIds與使用C#陣列

List<int> userIds = new List<int>();

我有代碼中插入它們到分貝的列表。
ExecuteSQL(sql)是我自己的函數,抽象了所有的數據庫特定的邏輯

string iSql = ""; 
foreach(int id in userIds){ 

iSql = "insert into users (id) values (" + id + ")"; 
ExecuteSQL(iSql); 

} 

我想插入所有這些在一個查詢,而不必調用像上面的循環, 這可能在SQL?

如果是這樣,那麼string iSql會是什麼樣子?

我發現Inserting multiple rows in a single SQL query?

但可能創造一個大的字符串。

,我發現其他文章要麼其他語言或只是困惑,因爲我無法它們與我的問題

(後來我纔可以照顧參數的,我只需要查詢)

+1

當你得到了一些答案,我認爲1000使用可以插入了值(1),(2)。如果超過1000則可以使用TVP。 http://msdn.microsoft.com/en-us/library/bb510489.aspx – Paparazzi

+1

參考http://lennilobel.wordpress.com/2009/07/29/sql-server-2008-table-valued-parameters-and -C-定製迭代器-A-比賽做在天堂/ – Paparazzi

回答

3
StringBuilder sb = new StringBuilder(); 
foreach(int id in userIds){ 
    sb.AppendLine("insert into users (id) values (" + id.ToString() + ");"); 
} 
ExecuteSQL(sb.ToString()); 

你真的應該使用參數化查詢。但上述將做你所需要的。

或備選地。

string iSql = string.Format("insert into users (id) values {0};", string.Join(",", userIds.Select(i => string.Format("({0})", i)))); 
ExecuteSQL(iSql); 
1

我建議你看看這個線程: How should I multiple insert multiple records?

有一個很好的方式做你想做的。

如果你仍然想使用一個字符串作爲查詢,你可以這樣做:

string iSql = "insert into users (id) values"; 
foreach(int id in userIds){ 
iSql += "(" + id + "),"; 

} 
ExecuteSQL(iSql); 

但說實話,我不喜歡它:)

編輯: Eoldre答案用的StringBuilder比我好。

1

您可以製作一個存儲過程並使用xml字符串發送插入的數據(userid)。在存儲過程中,您可以使用單個插入/選擇查詢並在表中插入所有數據。請使用以下代碼

create proc insertuser 
    @xml xml 
    as 

set @xml=N'<ids> 
<user><id>127531</id></user> 
<user><id>5445</id> </user> 
<user><id>477</id> </user> 
<user><id>785</id> </user> 
<user><id>456</id> </user> 
</ids>'          
declare @tbl table(id int) 

insert into users(id) 
select r.c.value('id[1]','int') 
from @xml.nodes('ids/user') as r(c) 
1

如果你使用它作爲一個答案
我用TVP加載了100萬行,這是快速
它基本上就像一個反向的DataReader

正如你得到了一些答案,你可以插入我認爲1000使用值(1),(2)。如果超過1000則可以使用TVP。

TVP

如果它是一個集合(而不是數據表),然後使用

SqlDataRecord

enter link description here