I need to write a CLR UDF that reads 开发者_C百科data from a table and loops through it, but most important storing data in double arrays (the table has only double values), afterwards I will use a math library to compute some things...
I have been searching but I found examples that connect to database, I want to make a .dll with C# code
, and call it from a stored proc.
An example I have found is this, but how would be the steps to make a dll instead connecting to db, And store double values in array?
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;
}
}
The most efficient way I think is to do it in two steps:
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
精彩评论