【问题标题】:Loop through a table in a CLR UDF C#循环遍历 CLR UDF C# 中的表
【发布时间】:2011-10-24 11:37:03
【问题描述】:

我需要编写一个从表中读取数据并循环遍历的 CLR UDF,但最重要的是将数据存储在 double 数组 中(表只有 double 值),之后我将使用数学库来计算一些东西......

我一直在搜索,但我找到了连接到数据库的示例,我想用C# code 创建一个 .dll,然后从存储的过程中调用它

我发现的一个例子就是这个,但是如何制作一个 dll 而不是连接到 db,并将双精度值存储在数组中?

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;

    }  
}

【问题讨论】:

  • 这个问题会取代你今天早些时候发布的问题吗?
  • 有点,但这是我认为的另一种解决方案......

标签: c# sql-server stored-procedures clr user-defined-functions


【解决方案1】:

我认为最有效的方法是分两步完成:

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

【讨论】:

  • 很酷的解决方案,只有一个问题,有没有办法避免使用conn.CreateCommand 进行连接,或者是否必须拥有它,如果是这样,那将是什么代码? SqlConnection conn = new SqlConnection(); conn.ConnectionString = "Context Connection=true"; SqlCommand cmd = new SqlCommand(); cmd.Connection = conn; 够了吗?
  • 是的,您也可以实例化一个 SqlCommand 并设置 Connection 属性。我更喜欢使用工厂方法 (CreateCommand),因为它只有 1 行,并且可能 IDbConnection 的一些其他实现可能需要对命令对象进行一些额外的初始化(在 SQL CLR 的上下文中不是这种情况代码,这样你就安全了)。
猜你喜欢
  • 1970-01-01
  • 2021-05-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多