我們新建一個DataBase project,然后建立一個UserDefinedFunctions,Code像這樣:
復(fù)制代碼 代碼如下:
1: /// summary>
/// SQLs the array.
/// /summary>
/// param name="str">The STR./param>
/// param name="delimiter">The delimiter./param>
/// returns>/returns>
/// 1/8/2010 2:41 PM author: v-pliu
[SqlFunction(Name = "CLR_Split",
FillRowMethodName = "FillRow",
TableDefinition = "id nvarchar(10)")]
public static IEnumerable SqlArray(SqlString str, SqlChars delimiter)
{
if (delimiter.Length == 0)
return new string[1] { str.Value };
return str.Value.Split(delimiter[0]);
}
/// summary>
/// Fills the row.
/// /summary>
/// param name="row">The row./param>
/// param name="str">The STR./param>
/// 1/8/2010 2:41 PM author: v-pliu
public static void FillRow(object row, out SqlString str)
{
str = new SqlString((string)row);
}
然后Bulid,Deploy一切OK后,在SSMS中執(zhí)行以下測試T-sql:
復(fù)制代碼 代碼如下:
DECLARE @array VARCHAR(max)
SET @array = '39,15,93,68,64,43,90,58,39,9,26,26,89,47,91,57,98,16,55,9,63,29,69,16,41,76,34,60,68,64,61,53,32,30,11,72,57,63,36,43,22,14,60,38,24,5,66,26,26,21,22,99,55,18,7,10,46,76,27,88,9,29,89,75,48,72,94,59,35,19,0,35,79,11,87,49,68,30,91,35,9,7,34,47,41,61,98,13,22,1,26,80,35,48,34,92,24,85,90,51' SELECT id FROM dbo.CLR_Split(@array,',')
我們來看它的Client Statistic:
接著我們執(zhí)行測試T-sql使用相同的array:
復(fù)制代碼 代碼如下:
DECLARE @array VARCHAR(max)
SET @array = '39,15,93,68,64,43,90,58,39,9,26,26,89,47,91,57,98,16,55,9,63,29,69,16,41,76,34,60,68,64,61,53,32,30,11,72,57,63,36,43,22,14,60,38,24,5,66,26,26,21,22,99,55,18,7,10,46,76,27,88,9,29,89,75,48,72,94,59,35,19,0,35,79,11,87,49,68,30,91,35,9,7,34,47,41,61,98,13,22,1,26,80,35,48,34,92,24,85,90,51'
SELECT item FROM strToTable(@array,',')
CTE實(shí)現(xiàn)的Split function的Client statistic:
通過對比,你可以發(fā)現(xiàn)CLR的performance略高于CTE方式,原因在于CLR方式有Cache功能,并且把一個復(fù)雜的運(yùn)算放到程序里比DataBase里更加高效。
您還可以參考:
Split string in SQL Server 2005+ CLR vs. T-SQL
Author:Petter Liu
您可能感興趣的文章:- 使用SqlServer CTE遞歸查詢處理樹、圖和層次結(jié)構(gòu)
- 在sqlserver中如何使用CTE解決復(fù)雜查詢問題
- 使用SQLSERVER 2005/2008 遞歸CTE查詢樹型結(jié)構(gòu)的方法
- SQLSERVER2005 中樹形數(shù)據(jù)的遞歸查詢
- sqlserver另類非遞歸的無限級分類(存儲過程版)
- SqlServer使用公用表表達(dá)式(CTE)實(shí)現(xiàn)無限級樹形構(gòu)建