## A simple math expression solver

 Author Message bkubicek SSCrazy Group: General Forum Members Points: 2489 Visits: 756 You earler post had a commet about the function only handles one expression at a time. That was kind of the point. In a select statement the function could be called for multiple expressions. That is actually the case in my situation. A table column contains a simple math expression. So using a function would allow me to get the answer to as many lines as would get returned in the select statement.Thanks for your posts.Ben jnichols-797753 Valued Member Group: General Forum Members Points: 51 Visits: 158 The method for evaluating algebraic equations is properly done through the use of reverse polish notation or more formally known as postfix notation. (It's referred to a reverse Polish notation because a Polish fellow figured it out) I've written these programs in COBOL, never thought about doing it in in T-SQL, maybe VB.NET. Could be a challenge. Through the use of cursors it might not be that difficult. I'll see if I can come up with something in a few days. You can use this method with a few modifications to evaluate formal logic as well. i.e is (A > B) or (C > B & D = B) a true statement. That can get very complex, trust me. So can algebra. jnichols-797753 Valued Member Group: General Forum Members Points: 51 Visits: 158 My earlier post was used in a software package to evaluare formulas in a table. The table was comprised of three "columns". The first column had the user friendly version of the forumla, the second column had the postfix form of that equation, the third was a key field used by an evaluation program to find the proper formula. The the evaluater program would read the table based on the key column and evaluate the second column streight away. Prettly slick, really. When I say user friendly think of (a + b) / c. I don't have access to my programs right now to show the exact form of that in postfix but t is something like: c!/!a!b!+ (the ! is used as a separator similar to a , in a .csv file). To get the user friendly formula into postfix you have to use stack processing which lends itself to cursor processing (I think). bkubicek SSCrazy Group: General Forum Members Points: 2489 Visits: 756 I would stay away from cursors if you decide to do it in t-sql. It might be better to use vb.net or c# and then use the clr. Although I believe you could still use a recursive function call if you were able to properly parse the equation.Ben jnichols-797753 Valued Member Group: General Forum Members Points: 51 Visits: 158 The key to this method is the formulas have already been converted to postfix notation and all the evaluator function has to do is peddle down the string evaluating the variables as you go and then applying the op code (+ - * /,etc.) to the variable. If you use an HP12c calculator you would be familiar with postfix notation. Formulas are generally pre-thought out and entered via key strokes. Once the operator exits that field the program would immediately format the formula into postfix noation ready for the processing program to select it and evaluate it. You have to think how something like this would be used. At a data entry level you don't have to worry about speed. paul.kohlmiller Forum Newbie Group: General Forum Members Points: 4 Visits: 27 I wonder if it would be fair to call this code a simplified RPN processor. Essentially you are taking infix notation and putting into a form that used to be required on some calculators. jnichols-797753 Valued Member Group: General Forum Members Points: 51 Visits: 158 Sort of. The code for evaluating a simple formula like mentioned early in this thread could be called a simplified RPN evaluator, I guess. I really didn't spend much time on it because I know intemately what an RPN process is all about. A real RPN processor can evaluate any depth algebraic equation. jorge33165-892186 Forum Newbie Group: General Forum Members Points: 6 Visits: 64 ------considering execution for many rows-----------------DECLARE @ExprCollection Table(expr VARCHAR(100) ) INSERT INTO @ExprCollection(expr) SELECT '2+1' UNION ALL SELECT '5*2' UNION ALL SELECT '6/3' DECLARE @genSql AS VARCHAR(MAX) CREATE TABLE #ExpValueTable ([value] INT,[Id_Exp] [VARCHAR](100) PRIMARY KEY) SELECT @genSql = CASE WHEN @genSql Is Null THEN ' INSERT INTO #ExpValueTable ([value],[Id_Exp]) ' + ' SELECT ' + expr + ' AS ExpValue,''' + expr +''' As Exp' ELSE @genSql + ' UNION SELECT ' + expr + ' AS ExpValue,''' + expr +''' As Exp' END FROM @ExprCollection GROUP BY expr EXEC(@genSql) SELECT * FROM #ExpValueTable --- OR JOIN YOUR TABLE TO THE TEMPORARY TABLE... AND BETTER USING THE TABLE PRIMARY KEY DROP TABLE #ExpValueTable jnichols-797753 Valued Member Group: General Forum Members Points: 51 Visits: 158 In this example the size of the table of literals is unlimited. However aditional coding is needed tu use variable names i.e. A, B, C, etc. A little fooling around with this thing and it might serve the most elementary uses. DECLARE @ExprCollection Table(expr VARCHAR(100) ) INSERT INTO @ExprCollection(expr) SELECT '2+1' UNION ALL SELECT '5*2' UNION ALL SELECT '6/3'drop table #ExpValueTable CREATE TABLE #ExpValueTable ([value] decimal(18,4),[Id_Exp] [VARCHAR](100) PRIMARY KEY)declare ExprCursor cursorfor select * from @ExprCollectiondeclare @Expr as varchar(100), @SQL varchar(max)open ExprCursor fetch next from ExprCursor into @Exprwhile @@Fetch_Status = 0BEGINset @SQL = ' INSERT INTO #ExpValueTable ([value],[Id_Exp]) SELECT ' + @expr + ' AS ExpValue,''' + @expr +''' As Exp' fetch next from ExprCursor into @Expr exec (@SQL)ENDclose ExprCursordeallocate ExprCursorselect * from #ExpValueTable kevin.a.larson Grasshopper Group: General Forum Members Points: 15 Visits: 43 When I ran Ben's code, I had some problems if I didn't leave spaces between the operators and the values. i.e., fn_simplemath('3 - 4') worked while fn_simplemath('3-4') failed... I suspect this would require a minor tweaking of some of the substring arguments. But trying to debug a recursive function can be a bit troublesome. It also occurred to me that since were were not concerned with operator precedence and simply calculating from left to right, we should be able to simply loop through the string without needing to be recursive.My approach was to create a string that duplicates the input except for replacing all the "acceptable" operator values with a single unique character, in my case I used a tilde(~). This second string can then be used to identify the position of all the operators in the original string and make it easier to parse out the individual operand valuesHere is my code:CREATE Function [dbo].[fn_simplemath2] ( @Expression1 varchar(255)) returns numeric(18,6)As BEGIN-- -- @Expression2 will duplicate @Expression1 with all operators replaced with ~ Declare @Expression2 varchar(255) Set @Expression2 = REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@Expression1,'-','~'),'+','~'),'*','~'),'/','~'),'%','~') -- -- Local variables Declare @PrevOpLoc int -- Location of previous operator Declare @NextOpLoc int -- Location of next operator Declare @OpChar Char(1) -- Current operator character Declare @Result numeric(18,6) -- Hold running calculation and final return value Declare @NextVal numeric(18,6) -- the next substring value to be used to modify result base on operator -- -- Find the first operator Set @NextOpLoc = CHARINDEX('~',@Expression2) -- -- Initialize @Result to the first substring, If there are no operators, move entire string to @Result Set @Result = CASE When @NextOpLoc = 0 then CAST(@Expression1 as numeric(18,6)) Else CAST(LEFT(@Expression1,@NextOpLoc-1) as numeric(18,6)) END -- -- Now we will loop until we run out of operators While @NextOpLoc <> 0 BEGIN -- Get the actual operator from @Expression1, pull out the next substring value Set @OpChar = SUBSTRING(@Expression1,@NextOpLoc,1) Set @PrevOpLoc = @NextOpLoc Set @NextOpLoc = CHARINDEX('~',@Expression2, @NextOpLoc + 1) Set @NextVal= Cast( SUBSTRING(@Expression1,@PrevOpLoc+1, Case When @NextOpLoc = 0 then LEN(@Expression1) Else @NextOpLoc-1 End - @PrevOpLoc) as numeric(18,6))-- -- Perform the appropriate operation Set @Result = Case @OpChar When '-' then @Result - @NextVal When '+' then @Result + @NextVal When '*' then @Result * @NextVal When '/' then @Result / @NextVal When '%' then @Result % @NextVal Else null End END Return @Result END

## Permissions

 You can't post new topics. You can't post topic replies. You can't post new polls. You can't post replies to polls. You can't edit your own topics. You can't delete your own topics. You can't edit other topics. You can't delete other topics. You can't edit your own posts. You can't edit other posts. You can't delete your own posts. You can't delete other posts. You can't post events. You can't edit your own events. You can't edit other events. You can't delete your own events. You can't delete other events. You can't send private messages. You can't send emails. You can read topics. You can't vote in polls. You can't upload attachments. You can download attachments. You can't post HTML code. You can't edit HTML code. You can't post IFCode. You can't post JavaScript. You can post emoticons. You can't post or upload images.

##### Select a forum
 SQL Server 2016      SQL Server 2016 - Administration      SQL Server 2016 - Development and T-SQL SQL Server 2014      Administration - SQL Server 2014      Development - SQL Server 2014 SQL Server 2012      SQL 2012 - General      SQL Server 2012 - T-SQL SQL Server vNext      SQL Server 14 - Administration      SQL Server 14 - Development SQL Server 2008      SQL Server 2008 - General      T-SQL (SS2K8)      June 2007 CTP      Working with Oracle      July CTP      SQL Server Newbies      Security (SS2K8)      SQL Server 2008 High Availability      SQL Server 2008 Administration      Data Corruption (SS2K8 / SS2K8 R2)      SQL Server 2008 Performance Tuning Cloud Computing      SQL Azure - Development      SQL Azure - Administration      Amazon AWS and other cloud vendors      General Cloud Computing Questions Reporting Services      Reporting Services      Reporting Services 2005 Administration      Reporting Services 2005 Development      Reporting Services 2008/R2 Administration      Reporting Services 2008 Development      SSRS 2012      SSRS 2014      SSRS 2016 Programming      Connecting      General      SMO/RMO/DMO      XML      Service Broker      Powershell      Testing      TFS/Data Dude/DBPro      SSDT      Continuous Integration, Deployment, and Delivery      R Services and R Language Data Warehousing      Integration Services      Strategies and Ideas      Analysis Services      Data Transformation Services (DTS)      Performance Point      Data Mining      PowerPivot      R language      Machine Learning Database Design      Disaster Recovery      Design Ideas and Questions      Relational Theory      Hardware      Virtualization SQLServerCentral.com      Anything that is NOT about SQL!      Contests!      Editorials      SQLServerCentral.com Announcements      SQLServerCentral.com Website Issues      Suggestions      Tag Issues with Content      Podcast Feedback      SQLServerCentral.com Test Forum      Articles Requested SQL Server 2005      Administering      Backups      Business Intelligence      CLR Integration and Programming.      Data Corruption      Development      Working with Oracle      SQL Server 2005 Compact Edition      SQL Server 2005 General Discussion      SQL Server 2005 Security      SQL Server 2005 Strategies      SS2K5 Replication      SQL Server Express      SQL Server 2005 Performance Tuning      SQL Server 2005 Integration Services      T-SQL (SS2K5)      SQL Server Newbies SQL Server 7,2000      Administration      Backups      Data Corruption      General      Globalization      In The Enterprise      Working with Oracle      Security      Strategies      SQL Server Newbies      Service Packs      SQL Server CE      Performance Tuning      Replication      Sarbanes-Oxley      T-SQL      SQL Server Agent SQL Server and other platforms      MySQL      Oracle      PostgreSQL      DB2      SQL Server and Sharepoint Older Versions of SQL (v6.5, v6.0, v4.2)      Older Versions of SQL (v6.5, v6.0, v4.2) Career      Certification      Employers and Employees      Events      Job Postings      Resumes and Job Hunters      Presentations and Speaking      Retired Members Testing Center      SQL Server Security Skills      Question of the Day (QOD) Microsoft Access      Microsoft Access Products and Books      Third Party Products         SQLCentric         Extreme Technologies.         Innovartis         Embarcadero         SQL Sentry         Sonasoft         Golden Gate Software         Idera         Red Gate Software         Quest Software         ApexSQL         Lumigent         CA      Discussions about Books         Discuss Programming Books          Discuss XML Books          Discuss T-SQL Books          Discuss Data Warehousing Books          Discuss DTS Books          Discuss SQL Server 2000 Books         Discuss SQL Server 7.0 Books Notification Services      Administration Article Discussions Future Versions      SQL 12