无法连接到 SQLCLR 中的外部数据库

Cannot connect to an external database in SQLCLR

我正在尝试创建一个连接到外部数据库和 运行 查询的函数。当我 运行 我的函数时出现此错误:

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.

我不认为我在做任何奇怪的事情,但这是我的代码。如果您发现异常情况,请告诉我。我真的不知道还能尝试什么。

 [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.

行向您的方法添加注释