2011-08-10 139 views
1

我需要编写一个CLR UDF,它从表中读取数据并循环遍历它,但最重要的是将数据存储在双列数组(表中只有双值),之后我会用一个数学库来进行一些事情......循环遍历CLR UDF中的表C#

我一直在寻找,但我发现,连接数据库的例子,我想打一个.dll与C# code把它从一个存储过程

我发现一个例子是这样的,但如何将是使一个DLL的步骤,而不是连接到数据库,并将其存储在阵列双值?

using System; 
using System.Data; 
using System.Data.SqlClient; 
using System.Data.SqlTypes; 
using Microsoft.SqlServer.Server; 
using System.Text; 


public partial class StoredProcedures 
{ 
    [Microsoft.SqlServer.Server.SqlProcedure] 
    public static void CLR_StoredProcedure3() 
    { 
     SqlConnection conn = new SqlConnection(); 
     conn.ConnectionString = "Context Connection=true"; 

     SqlCommand cmd = new SqlCommand(); 
     cmd.Connection = conn; 

    } 
} 
+0

请问这个问题代替你今天已经发布早一点的人吗? – stakx

+0

种,但是这一次是其他解决方案,我thiught ... – cMinor

回答

2

最有效的方式,我认为是这样做的两个步骤:

int count; 
using (SqlCommand cmdCount = conn.CreateCommand()) 
{ 
    cmdCount.CommandText = "SELECT COUNT(*) FROM [MyTable]"; 
    count = (int)cmdCount.ExecuteScalar(); 
} 

// knowing the number of rows we can efficiently allocate the array 
double[] values = new double[count]; 

using (SqlCommand cmdLoad = conn.CreateCommand()) 
{ 
    cmdLoad.CommandText = "SELECT * FROM [MyTable]"; 

    using(SqlDataReader reader = cmdLoad.ExecuteReader()) 
    { 
     int col = reader.GetOrdinal("MyColumnName"); 
     for(int i = 0; i < count && reader.Read(); i++) 
     { 
      values[i] = reader.GetDouble(col); 
     } 
    } 
} 

// do more processing on values[] here 
+0

冷静的解决方案,只有一个问题,有没有办法避免如果是这样,使用'conn.CreateCommand'或者是强制要求有连接,会是什么成为那个代码? 'SqlConnection conn = new SqlConnection(); conn.ConnectionString =“Context Connection = true”; SqlCommand cmd = new SqlCommand(); cmd.Connection = conn;'就够了? – cMinor

+0

是的,你可以实例化一个'SqlCommand'并设置'Connection'属性。我更喜欢使用工厂方法(CreateCommand),因为它只有1行,并且*可能*某些IDbConnection的其他实现可能需要对命令对象进行一些额外的初始化(在SQL CLR代码的上下文中并非如此,所以您安全)。 – Serguei