Skip to main content
 首页 » 编程设计

c#之如何在存储过程参数中传递多条记录

2024年02月13日14arxive

我在 Sql Server 2005 数据库中创建了一个存储过程 sp_UpdateRate,在我的 C# 应用程序中我有一个包含多个速率的十进制数组。现在,我想将该数组传递到我的存储过程中。数组的长度不是静态的。我该怎么做呢。 sql参数中有数组类型吗? 这是我的代码:

decimal[] rates = new decimal[lst.Items.Count]; //lst is the ListBox control that containing list of rate. 
for (int i=0;i<lst.Items.Count;i++) 
{ 
    rates[i]=Convert.ToDecimal(lst.Items[i]); 
} 
 
SqlCommand cmd = Cnn.CreateCommand;  //Cnn is the SqlConnection class object 
cmd.CommandText = "sp_UpdateRate"; 
cmd.CommandType = System.Data.CommandType.StoredProcedure; 
cmd.ExecuteNonQuery(); 

我的存储过程在这里

Alter Procedure sp_UpdateRate(@rate decimal(9,2)) 
AS 
BEGIN 
     --I want to Update my rates here. 
     Update tblRate SET LastUpdate=GetDate(), NewRate=(@rate * 1.658) Where rate=@rate 
END 

请您参考如下方法:

从 SQL Server 2008 开始,您可以传递表变量...

http://www.techrepublic.com/blog/the-enterprise-cloud/passing-table-valued-parameters-in-sql-server-2008/

不幸的是,您仍在使用 SQL 2005。我建议,如果可以的话,升级到 SQL Server 2008。如果这不是一个选项,您可以使用 XML 数据类型。

Problem passing XML Parameter to SQL Server Stored Procedure

希望能有所帮助...没有 xml 数据类型...旧的 SQL 2000 天...您必须这样做...http://www.codeproject.com/Articles/7485/Inserting-XML-formatted-data-into-SQL-Server-2000

甚至在此之前......您可以使用 CSV(字符串)然后使用 Split 函数(found here)。