日期:2014-05-17 浏览次数:20448 次
DROP TABLE #temp
CREATE TABLE #temp(id INT, expression VARCHAR(MAX))
INSERT #temp values(1, 'if(4/(if(2>1,2,1)+2) = 0,if(6/(3+3)=1,3,2),4/(4+4))')
--SQL
;WITH cte1 AS
(
SELECT
id,
pos = CHARINDEX('(', expression),
word = CAST(LEFT(expression, CHARINDEX('(', expression) - 1) AS NVARCHAR(MAX)),
name = 1,
Split = CAST(STUFF(expression + '(', 1, CHARINDEX('(', expression + '('), '') AS NVARCHAR(MAX))
FROM #temp
UNION ALL
SELECT
id,
pos = a.pos + CHARINDEX('(', Split),
word = CAST(LEFT(Split, CHARINDEX('(', Split) - 1) AS NVARCHAR(MAX)),
name = 1,
Split = CAST(STUFF(Split, 1, CHARINDEX('(', Split), '') AS NVARCHAR(MAX))
FROM cte1 a
WHERE Split > ''
),
cte2 AS
(
SELECT
id,
pos = CHARINDEX(')', expression),
word = CAST(LEFT(expression, CHARINDEX(')', expression) - 1) AS NVARCHAR(MAX)),
name = -1,
Split = CAST(STUFF(expression + ')', 1, CHARINDEX(')', expression + ')'), '') AS NVARCHAR(MAX))
FROM #temp
UNION ALL
SELECT
id,
pos = a.pos + CHARINDEX(')', Split),
word = CAST(LEFT(Split, CHARINDEX(')', Split) - 1) AS NVARCHAR(MAX)),
name = -1,
Split = CAST(STUFF(Split, 1, CHARINDEX(')', Split), '') AS NVARCHAR(MAX))