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

时间:2015-05-06 23:05:01

标签: c# sql sql-server sqlclr

我正在尝试创建一个连接到外部数据库并运行查询的函数。当我运行我的功能时,我收到此错误:

  

在此上下文中不允许数据访问。上下文是未使用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 "";
 }

1 个答案:

答案 0 :(得分:1)

您需要在string=String.format("%f degrees Celsius", convertToCelsius(temp)); 行中为方法添加注释。