字串分割是 T-SQL 常見需求。SQL Server 2008 可透過 CLR 整合 撰寫高效能分割函數,亦可用 CTE 遞歸 純 T-SQL 實作。本文實測兩種方式在相同資料下的 Client Statistics 差異,分析效能優劣。
[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]);
}
public static void FillRow(object row, out SqlString str)
{ str = new SqlString((string)row); }
部署後於 SSMS 執行:
DECLARE @array VARCHAR(max) = '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, ',');

-- 假設已建立 strToTable 函數
SELECT item FROM strToTable(@array, ',');

| 指標 | CLR_Split | CTE strToTable |
|---|---|---|
| CPU 時間 (ms) | 較低 | 較高 |
| 經過時間 (ms) | 較低 | 較高 |
| 邏輯讀取 | 較少 | 較多 |
結論:CLR 方式效能略優於 CTE,主因在於: