这是我的clr代码,其中我收到了上述错误。我尝试添加参考System.Data.Entity但问题仍然存在。
using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
using System.Linq;
public partial class StoredProcedures
{
[Microsoft.SqlServer.Server.SqlProcedure]
public static void StoredProcedure1()
{
// Put your code here
DataTable dt = BuildTable();
DataTable dtTempDates = GetBlankDataTableWithDateColumns(dt);
for (int col = 1; col < dtTempDates.Columns.Count; col++)
{
string columnName = dtTempDates.Columns[col].ColumnName;
string ymd = columnName.Substring(columnName.IndexOf("|") + 1);
Double sum = dt.AsEnumerable().Where(r => !String.IsNullOrEmpty(r[columnName].ToString())).Sum(r => (int)r[columnName]);
}
}
private static DataTable GetBlankDataTableWithDateColumns(DataTable dt)
{
DataTable datatable = new DataTable();
datatable.Columns.Add("COUNTRY", typeof(string));
var distinctDateValues = dt.AsEnumerable()
.Select(row => DateTime.Parse(row.Field<string>("DATE")))
.OrderByDescending(x => x)
.Distinct()
.ToList();
int totalDateCount = System.Linq.Enumerable.Count(distinctDateValues);
for (int row = 0; row < totalDateCount; row++)
{
string date = distinctDateValues[row].Date.ToString("M/d/yyyy");
datatable.Columns.Add("Amount|" + date, typeof(int));
}
return datatable;
}
private static DataTable BuildTable()
{
DataTable datatable = new DataTable("Country");
datatable.Columns.Add("COUNTRY", typeof(string));
datatable.Columns.Add("CODE", typeof(string));
datatable.Columns.Add("DATE", typeof(string));
datatable.Columns.Add("AMOUNT", typeof(double));
datatable.Rows.Add(new Object[] { "Ukraine", "0295", "08/16/2013", 122794 });
datatable.Rows.Add(new Object[] { "USA and Canada", "0614", "08/17/2013", 5671 });
datatable.Rows.Add(new Object[] { "Algeria", "123", "08/17/2013", 26570 });
datatable.Rows.Add(new Object[] { "Japan", "789", "08/17/2013", 1883 });
datatable.Rows.Add(new Object[] { "India", "786", "08/17/2013", 288 });
datatable.Rows.Add(new Object[] { "India", "786", "08/17/2013", 238 });
datatable.Rows.Add(new Object[] { "Ukraine", "0295", "08/18/2013", 3568 });
datatable.Rows.Add(new Object[] { "USA and Canada", "0614", "08/18/2013", 3668 });
datatable.Rows.Add(new Object[] { "Algeria", "123", "08/18/2013", 785 });
return datatable;
}
};
我还尝试添加System.Data.DataSetExtensions.dll,但是当我在SQL上部署sp并运行存储过程时,它给出了错误:版本不同,GAC中不存在程序集。我无法覆盖/改变组件,因为它正在其他项目中使用。
任何人都可以建议解决所有这些问题的解决方法。
答案 0 :(得分:0)
我确定你在旅行中遇到过这个旧线程,因为你提到将DLL加载到SQL Server中。
LINQ on a DataTable IN a CLR Stored Procedure
正如Lasse所提到的,根据one of the first comments in that thread,这是一个非常简单的过程。我已经使用这种方法在我自己的项目中实现了这个:
public static IEnumerable<DataRow> AsEnumerable(this DataTable dt)
{
foreach (DataRow r in dt.Rows) yield return r;
}
要在LINQ查询中使用它,语法与内置AsEnumerable
不同,您不能使用d.Field<string>("ColumnName")
:
DataTable _tblData;
var tbl = from d in _tblData.AsEnumerable()
select new { ColumnName = d["ColumnName"] };