简体   繁体   中英

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.

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行向方法添加注释。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM