傳遞到 LEFT 或 SUBSTRING 函數的參數長度無效該 Table 是跑樹狀結構資料,根結點為 A0,節點是以 A0_A1_A2 型式來記錄,會透過 SUBSTRING 來取得父節點,語法如下
DECLARE @TreePath varchar(100) = 'A0_A1_A2'
SELECT SUBSTRING(@TreePAth , 1 , LEN(@TreePath)-3) -- 取得 A0_A1
該問題就很明顯,以 A0 節點去進行 substring 時,長度減 3 就一定會拋出錯誤
實際 TSQL 概念語法
SELECT *
FROM
(
SELECT *
SUBSTRING(TreePath , 1 , LEN(TreePath)-3) AS TreePath
FROM 樹狀Table
WHERE Condition1
) AS T1
JOIN
(
SELECT *
SUBSTRING(TreePath , 1 , LEN(TreePath)-3) AS TreePath
FROM 樹狀Table
WHERE Condition2
) AS T2 ON T1.TreePath = T2.TreePath
觀察估計執行計畫
從執行計畫中觀察,可以發現 T1 Table 先跑,透過 Compute Scalar (substring 抓父節點) 跑 Nested Loops 去篩選 T2 Table 資料,所以才會拋出錯誤
沒有留言:
張貼留言