Jam*_*mes 5 .net c# sql-server sqlclr user-defined-functions
我正在使用CLR表值函数来SELECT并返回使用许多变量的复杂数据库搜索的结果.
文档显示您以类似于此的方式构建此类函数:
public partial class UserDefinedFunctions
{
private class ResultRow
// This class holds a row which we want to return.
{
public SqlInt32 CustId;
public SqlString Name;
public ResultRow(SqlInt32 custId_, SqlString name_)
{
CustId = custId_;
Name = name_;
}
}
[SqlFunction(
DataAccess = DataAccessKind.Read,
FillRowMethodName = "Test_FillRow",
TableDefinition = "CustId int" +
"Name nvarchar(50)")]
public static IEnumerable Test()
// This function contains the actual logic.
{
ArrayList results = new ArrayList();
using (SqlConnection connection = new SqlConnection("context connection=true"))
{
connection.Open();
using (SqlCommand select = new SqlCommand(
"SELECT TOP 100 custid, name FROM Customers",
connection))
{
using (SqlDataReader reader = select.ExecuteReader())
{
while (reader.Read())
{
results.Add(new ResultRow(
reader.GetSqlInt32(0), // CustId
reader.GetSqlString(1) // Name
));
}
}
}
}
return results;
}
public static void Test_FillRow(
object resultsObj,
out SqlInt32 custid,
out SqlString name)
// This function takes a row and tells SQL Server what variables we want to
// return from it and what types it contains.
{
ResultRow selectResults = (ResultRow)resultsObj;
custid = selectResults.CustId;
name = selectResults.Name;
}
}
Run Code Online (Sandbox Code Playgroud)
问题是,它相当重复.首先在SqlFunction块中定义表.然后,当您在返回的结果中添加或删除列时,您必须确保更新它并且
我正在研究这样一个函数,它接受20多个参数,返回更多行,并包含这8个可能出错的地方.八.所有的错误都是微不足道的,很容易修复,但是制作它们非常容易,因为代码中有很多地方我必须手动保持同步.
这是对DRY的违反,但我不知道如何消除重复.是否有更简洁的方法来编写CLR表值函数?
如果将 ResultRow 替换为 object[],则可以使用 reader.GetValues(object[]) 并消除在 FillRow() 之前必须知道行中的内容,然后 FillRow 负责了解字段在原始查询。
这确实是一种权衡,你可以放弃一直使用强类型,以换取不必一直使用强类型,但很难两者兼顾:-)