2013-11-15 97 views
0

我想根據控件編號的輸入自動添加參數。使用c#在存儲過程中添加參數

下面的代碼會給我sp_INSERT @ COL5,sp_INSERT @ COL4,等等...

control = 5; 

while(1<=control) 
column = '@COL' 
string setValues = "sp_INSERT'" + column + control + "';" 

control = control - 1; 

我想達到什麼是sp_INSERT @ COL5,@ COL4,@ COL3,等等.. 。

+1

旁註:你應該** **不使用'sp_'前綴爲您的存儲過程。微軟已經保留了這個前綴以供自己使用(參見*命名存儲過程*)](http://msdn.microsoft.com/en-us/library/ms190669%28v=sql.105%29.aspx),以及你將來有可能冒着名字衝突的風險。 [這對你的存儲過程性能也是不利的](http://www.sqlperformance.com/2012/10/t-sql-queries/sp_prefix)。最好只是簡單地避免使用'sp_'並將其他內容用作前綴 - 或者根本沒有前綴! –

+0

不,如果它甚至編譯,該代碼將永遠循環分配'列'價值'「@COL」'...... –

+0

你標記了這個C#,但你發佈的代碼不是。 – oerkelens

回答

0

Just ... loop?

int control = 5; 
string colPrefix = "@COL"; 
var sql = new StringBuilder("sp_INSERT ").Append(colPrefix).Append(control); 
// note first item has different format due to comma 
for(int i = control - 1; i > 0; i--) 
{ 
    sql.Append(", ").Append(colPrefix).Append(i); 
} 
sql.Append(';'); 
string s = sql.ToString(); 
0

簡單的循環,而不是一個完整的解決方案,但它可能會幫助...

string myString = "INSERT "; 
for (int i = 5; i > 0; i--) 
    myString = string.Format("{0} @COL{1}, ", myString, i);