[英]Cannot connect to an external database in SQLCLR
I am trying to create a function that will connect to an external database and run a query. 我正在尝试创建一个将连接到外部数据库并运行查询的函数。 When I run my function I am getting this error: 当我运行函数时,出现此错误:
Data access is not allowed in this context. 在这种情况下,不允许数据访问。 Either the context is a function or method not marked with DataAccessKind.Read or SystemDataAccessKind.Read, is a callback to obtain data from FillRow method of a Table Valued Function, or is a UDT validation method. 上下文是未用DataAccessKind.Read或SystemDataAccessKind.Read标记的函数或方法,是从表值函数的FillRow方法获取数据的回调,还是UDT验证方法。
I don't think that I am doing anything strange, but here is my code. 我不认为我在做任何奇怪的事情,但这是我的代码。 Please let me know if you spot something odd. 如果您发现一些奇怪的东西,请告诉我。 I really don't know what else to try. 我真的不知道还能尝试什么。
[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
行向方法添加注释。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.