SQLSERVER2008中CTE的Split与CLR的性能比较

前端之家收集整理的这篇文章主要介绍了SQLSERVER2008中CTE的Split与CLR的性能比较前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我们新建一个DataBase project,然后建立一个UserDefinedFunctions,Code像这样:
<div class="codetitle"><a style="CURSOR: pointer" data="47900" class="copybut" id="copybut47900" onclick="doCopy('code47900')"> 代码如下:

<div class="codebody" id="code47900">
1: ///
/// sqls the array.
///

/// <param name="str">The STR.
/// <param name="delimiter">The delimiter.
///
/// 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]);
}
///
/// Fills the row.
///

/// <param name="row">The row.
/// <param name="str">The STR.
/// 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中执行以下测试T-sql:
<div class="codetitle"><a style="CURSOR: pointer" data="39614" class="copybut" id="copybut39614" onclick="doCopy('code39614')"> 代码如下:
<div class="codebody" id="code39614">
DECLARE @array VARCHAR(max)
SET @array = '39,15,93,68,64,43,90,58,39,9,26,89,47,91,57,98,16,55,63,29,69,41,76,34,60,61,53,32,30,11,72,36,22,14,38,24,5,66,21,99,18,7,10,46,27,88,75,48,94,59,35,19,79,87,49,13,1,80,92,85,51' SELECT id FROM dbo.CLR_Split(@array,',')

我们来看它的Client Statistic:

接着我们执行测试T-sql使用相同的array:

代码如下:
DECLARE @array VARCHAR(max)
SET @array = '39,51'
SELECT item FROM strToTable(@array,')

CTE实现的Split function的Client statistic:

通过对比,你可以发现CLR的performance略高于CTE方式,原因在于CLR方式有Cache功能,并且把一个复杂的运算放到程序里比DataBase里更加高效。

您还可以参考:
PHP/DataMgmt/DBProgramming/split-string-in-sql-server-2005-clr-vs-t">Split string in sql Server 2005+ CLR vs. T-sql
Author:Petter Liu

猜你在找的MsSQL相关文章