【发布时间】:2015-05-06 23:05:00
【问题描述】:
我正在尝试创建一个连接到外部数据库并运行查询的函数。当我运行我的函数时,我收到了这个错误:
在此上下文中不允许数据访问。上下文要么是未使用 DataAccessKind.Read 或 SystemDataAccessKind.Read 标记的函数或方法,要么是从表值函数的 FillRow 方法获取数据的回调,要么是 UDT 验证方法。
我不认为我在做任何奇怪的事情,但这是我的代码。如果你发现一些奇怪的东西,请告诉我。我真的不知道还能尝试什么。
[Microsoft.SqlServer.Server.SqlFunction]
public static SqlString createFile()
{
string theQuery = "SELECT * FROM A_TABLE;";
string theConnection = "Data Source=serverName;Initial Catalog=DatabaseBane;Persist Security Info=True;User ID=login;Password=thePassword";
SqlConnection DBConnect = new SqlConnection(theConnection);
try
{
//My code is breaking here************************************
DBConnect.Open();
}
catch (Exception e)
{
return "Happening in the connect: " + e.Message;
}
SqlDataAdapter dataAdapter = new SqlDataAdapter(theQuery, DBConnect);
DataTable HRNdata = new DataTable();
dataAdapter.Fill(HRNdata);
FileStream stream = new FileStream(@"C:\TestFiles\demo.xls", FileMode.OpenOrCreate);
ExcelWriter writer = new ExcelWriter(stream);
writer.BeginWrite();
Dictionary<string, int> noteDict = new Dictionary<string, int>();
foreach (DataRow r in HRNdata.Rows)
{
try
{
noteDict.Add(r["Note"].ToString(), 1);
}
catch
{
noteDict[r["Note"].ToString()] += 1;
}
}
int counter = 1;
foreach (KeyValuePair<string, int> pair in noteDict)
{
writer.WriteCell(1, counter, pair.Key);
writer.WriteCell(2, counter, pair.Value);
counter++;
}
writer.EndWrite();
stream.Close();
try
{
DBConnect.Close();
}
catch (Exception e)
{
return e.Message;
}
return "";
}
【问题讨论】:
-
似乎你将不得不用
DataAccessKind.Read之类的东西来注释你的方法。此外,这可能会有所帮助:stackoverflow.com/questions/591191/…. -
哇。非常感谢!我知道我需要一双额外的眼睛!它总是让我得到格式化的东西。改变这个就成功了 [Microsoft.SqlServer.Server.SqlFunction(DataAccess = DataAccessKind.Read)]] public static SqlString createFile() {
-
@John 如果您找到了问题的解决方案,请将其添加为答案!这样其他有类似问题的人也可以看到解决方案。
标签: c# sql sql-server sqlclr