2012-05-04 78 views
1

至於這個問題,在這裏SQL CLR return two new columns我試圖創建一個簡單的SQL CLR函數,在那裏我可以通過兩個字符串到函數,並將它傳遞我回兩個新列。SQL Server的CLR TVF返回兩個新列插入數據流

所以說,我有以下數據: -

Col A  Col B 
Bob  Joe 
Jane  John 

我希望能柱A和色柱B傳遞給CLR函數,並讓它返回這樣的事情(其中山口C和d是新列): -

Col A  Col B  Col C  Col D 
Bob  Joe  BobCLR JoeCLR 
Jane  John  JaneCLR JohnCLR 

我有下面的代碼: -

[SqlFunction(FillRowMethodName = "FillRow")] 
    public static IEnumerable MyCLRFunction(string A, string B) 
    { 
     String[] values = new String[2]; 
     values[0] = A+"CLR"; 
     values[1]= B+"CLR"; 

     return values; 
    } 

     private static void FillRow(Object obj, out string C, out string D) 
     { 
      String[] row = (object[])obj; 
      C = (string)row[0]; 
      D = (string)row[1]; 
     } 

我可以在SQL大會登記使用CREATE ASSEMBLY

如下我可以創建功能在SQL Server確定服務器確定: -

CREATE FUNCTION dbo.MyCLRFunction(@a [nvarchar](4000), @b [nvarchar](4000)) 
RETURNS TABLE 
(c [nvarchar](4000) null, d [nvarchar](4000) null) with execute as caller 
AS 
EXTERNAL NAME [MyNamespace].[CLRFunctions].[MyCLRFunction] 

然而,當我這樣做: -

SELECT * FROM MyCLRFunction('Bob','Joe') 

即時得到: -

Msg 6260, Level 16, State 1, Line 1 
An error occurred while getting new row from user defined Table Valued Function : 
System.InvalidCastException: Unable to cast object of type 'System.String' to type 'System.String[]'. 
System.InvalidCastException: 
    at CLRFunctions.FillRow(Object obj, String& C, String& D) 

回答

1

好設法現在做這個內一個IEnumerable使用KeyValuePair。

using System; 
using System.Collections; 
using System.Collections.Generic; 
using System.Data.SqlTypes; 
using Microsoft.SqlServer.Server; 

public class CLRFunctions 
{ 

    private static IEnumerable<KeyValuePair<double, double>> CoordinatesEnumerable(double Lat, double Long) 
    { 
     return new Dictionary<double, double> { { Lat, Long } }; 
    } 

    [SqlFunction(FillRowMethodName = "FillRow")] 
    public static IEnumerable ToLatLong(double East, double North) 
    { 
     return CoordinatesEnumerable(East, North); 
    } 

    private static void FillRow(Object obj, out SqlDouble Lat, out SqlDouble Long) 
    { 
     KeyValuePair<double, double> Coordinates = (KeyValuePair<double, double>)obj; 
     Lat = new SqlDouble(Coordinates.Key); 
     Long = new SqlDouble(Coordinates.Value); 
    } 

} 
1

我從來沒有做過一個CLR存儲過程那樣,你似乎是返回一個字符串數組,而不是一個原子串。

RETURNS TABLE (C nvarchar的空值,d爲nvarchar空)

同樣,只是乍一看,c和d在上述期待字符串,而不是一個數組元素。