2016-05-04 42 views
0

我需要定期从下面的链接下载数据并将其保存到MS数据库中。我使用WebClient类创建了CLR函数,但everythig在一行中,我需要将它分开。在CLR函数中返回数组

我想到了将数据保存在数组中,使用split并在循环中返回它,但我不知道如何逐行返回以将其保存在数据库中。

public partial class UserDefinedFunctions 
{ 

private static readonly WebClient webClient = new WebClient(); 

[Microsoft.SqlServer.Server.SqlFunction] 
public static SqlString DownloadSynop(string uri) 
{ 
    string synop = webClient.DownloadString(uri); 
    string[] lines = synop.Split(new string[] { Environment.NewLine, "\n", "\"r" }, StringSplitOptions.None); 

    for (int i=0; i<lines.Length - 1; i++) 
    { 
     string kod = lines[i];   

    } 

    return new SqlString(kod); //problem 
} 
} 

回答

0

SQL Server不真正支持“阵列”每说和一般我会建议您开发解析网页一个单独的服务或应用程序,然后只需将所需的数据到格式化的表格上需要。使用CLR查询网页意味着您必须将CLR作为不安全发布到SQL Server。某些组织不允许CLR在其服务器上标记为不安全。

话虽如此,你可以创建一个表值CLR函数。这将允许你像你的标准表一样从你的函数中查询你的结果。下面是如何可以实现这样的代码示例:

public partial class UserDefinedFunctions 
    { 

     private struct Record 
     { 
      public int RowNr; 
      public string SampleValue; 
     } 


     [SqlFunction(FillRowMethodName = "MyClrTableValuedFunction_FillRow", 
      TableDefinition = "[RowNr] INT, [SampleValue] NVARCHAR(50)")] 
     public static IEnumerable MyClrTableValuedFunction() 
     { 
      ArrayList list = new ArrayList(); 

      for (int sampleRowNr = 0; sampleRowNr < 100; sampleRowNr++) 
      { 
       Record sampleRecord = new Record(); 
       sampleRecord.RowNr = sampleRowNr; 
       sampleRecord.SampleValue = string.Format("Sample Value: {0}", sampleRowNr); 

       list.Add(sampleRecord); 
      } 

      return list; 
     } 


     public static void MyClrTableValuedFunction_FillRow(Object obj, out SqlInt32 rowNr, out SqlString sampleValue) 
     { 
      Record record = (Record)obj; 

      rowNr = record.RowNr; 
      sampleValue = record.SampleValue; 
     } 
    } 

您可以在SQL Server中调用函数作为一个标准的select语句如下:

SELECT [RowNr] 
      ,[SampleValue] 
    FROM [dbo].[MyClrTableValuedFunction]()