2010-03-16 93 views
3

如何返回帶有標準SQL CLR的標識列拆分UDF例如下面的代碼將返回一個表,其中字符串值由分隔符分隔,我需要以某種方式返回標識列作爲好。SQL CLR中的標識列拆分UDF

<SqlFunction(FillRowMethodName:="FillRow", TableDefinition:="value nvarchar(4000)")> _ 
Public Shared Function GetStrings(ByVal str As SqlString, ByVal delimiter As SqlString) As IEnumerable 
    If (str.IsNull OrElse delimiter.IsNull) Then 
     Return Nothing 
    Else 
     Return str.Value.Split(CChar(delimiter)) 
    End If 
End Function 
Public Shared Sub FillRow(ByVal row As Object, ByRef str As String) 
    str = CType(row, String).Trim() 
End Sub 

回答

3

就CLR UDF而言,由於您自己生成所有行,因此「標識」沒有任何特別的含義。你想要的只是一個櫃檯。

簡單的答案是隻在當場生成索引,然後發送合成值IEnumerable。所以像這樣:

[SqlFunction(FillRowMethodName = "FillMyRow", 
    TableDefinition = "ID int, Value nvarchar(4000)")] 
public static IEnumerable GetStrings(SqlString str, SqlString delimiter) 
{ 
    if (str.IsNull || delimiter.IsNull) 
    { 
     return null; 
    } 

    string[] values = str.Value.Split(delimiter.Value.ToCharArray()); 
    StringPair[] results = new StringPair[values.Length]; 
    for (int i = 0; i < values.Length; i++) 
    { 
     results[i] = new StringPair(i + 1, values[i]); 
    } 
    return results; 
} 

public static void FillMyRow(object row, ref int id, ref string value) 
{ 
    StringPair pair = (StringPair)row; 
    id = pair.ID; 
    value = pair.Value; 
} 

public class StringPair 
{ 
    public StringPair(int id, string value) 
    { 
     this.id = id; 
     this.value = value; 
    } 

    public int ID { get; private set; } 
    public string Value { get; private set; } 
} 

這與標識列完全相同;你只是增加一個計數器的ID,從數字1開始。

你可能還想考慮一下代理ID可以在SQL本身生成ROW_NUMBER,所以它可能沒有必要這樣做所有。這將是我個人的選擇,但如果您需要在CLR輸出中執行此操作,上面的代碼應該可以做到。

+0

ROW_NUMBER將如何工作?您將通過以分隔字符串的形式獲取原始訂單的內容是什麼? – 2013-10-31 17:27:49