Thursday, February 03, 2011

TSQL Challenge 48 - Parse and evaluate Arithmetic Expressions using TSQL

The primary goal of this challenge is to demonstrate the power of Recursive CTEs introduced in SQL Server 2005. Recursive CTEs allow you to implement almost any algorithm in a single TSQL statement. This challenge is to parse and evaluate arithmetic expressions using TSQL.

Source Data


id expr x0 dx points --- --------- ---- ----- ------ 1 1+2*(4+x) 0 0.1 4 2 x^2/2 0 0.1 4 3 x^x 0 10 4

Expected Results


expr x value --------- ------ -------------------------- 1+2*(4+x) 0 9 1+2*(4+x) 0.1 9.2 1+2*(4+x) 0.2 9.4 1+2*(4+x) 0.3 9.6 x^2/2 0 0 x^2/2 0.1 0.005 x^2/2 0.2 0.02 x^2/2 0.3 0.045 x^x 0 1 x^x 10 10000000000 x^x 20 1.048576E+26 x^x 30 2.05891132094649E+44

Notes“expr” could be any valid expression using single digit constants, the single variable x, the operators + - * / ^ and possibly parentheses
“x0” is the starting position on the x-axis
“dx” is the increment for each value
“points” is the number of values to generate which will be greater than zero
The result should be sorted by expr, x
All calculations should be done using full float precision and number range. The display of numbers in the value column should be in the format generated by a float(53) data type.

Read more: Beyond Relational