Say I have a bunch of rows in a DB (SQLServer 2008 in this case) that can be used to create equations.
-----------------------------------------------------
OperationID | EquationID | Operation | Amount | Order
-----------------------------------------------------
1 | 1 | + | 12 | 1
2 | 1 | + | 12 | 2
3 | 2 | / | 2 | 3
4 | 2 | + | 12 | 1
5 | 2 | - | 2 | 2
-----------------------------------------------------
Run Code Online (Sandbox Code Playgroud)
I need come up with a way to evaluate the equations in this table.
Equation 1: 12 + 12 = 24
Equation 2: (12 - 2)/2 = 5
我想不出一种方法来获得这些结果而不迭代行.我知道如何执行此操作的唯一方法是使用游标或使用临时表和while循环.有没有更好的方法来做到这一点?如果不是通常会执行更好的游标或循环?
注意:这有点简化,在项目的这个阶段,我们只能猜测数据的样子.假设每个'方程'将有大约100到1000次操作,并且每天将有几千个"方程式"需要处理.
事实证明,在得出运行总计方面,递归 CTE 的性能优于循环。这实际上只是一个变量运算符的运行总计,因此性能优势应该适用于此。
创建行为类似于循环的递归 CTE 的方法如下:
;WITH cte AS (
SELECT equation, number, order FROM table WHERE order = 1
UNION ALL
SELECT table.equation,
CASE WHEN table.operation = '+' THEN cte.number + table.number
WHEN table.operation = '-' THEN cte.number - table.number END AS number, --etc.
table.order FROM table INNER JOIN cte ON table.order = cte.order + 1 AND table.equation = cte.equation
)
SELECT equation, number, order
FROM cte
OPTION (MAXRECURSION 1000);
Run Code Online (Sandbox Code Playgroud)
第一个 SELECT 获取最左边的数字,UNION all 对它返回的数字执行以下操作。maxrecursion 选项将一个方程中的运算次数限制为 1000。当然,您可以将其设置得更高。
这个答案有些不完整,因为最终的选择查询将返回中间结果。不过,过滤起来相当简单。
| 归档时间: |
|
| 查看次数: |
3481 次 |
| 最近记录: |