Recent PostsRecent Posts Popular TopicsPopular Topics
 Home Search Members Calendar Who's On

 A simple math expression solver Rate Topic Display Mode Topic Options
Author
 Message
 Posted Wednesday, November 23, 2011 9:23 AM
 SSC Rookie Group: General Forum Members Last Login: 2 days ago @ 7:37 AM Points: 35, Visits: 142
 If the specification is for a single operation with an integer on either side ...`CREATE FUNCTION [SimpleMath](@expression VARCHAR(max))RETURNS INTASBEGIN DECLARE @position INT, @operator CHAR(1), @left INT, @right INT, @result INT SELECT @position = PATINDEX('%[*/+-]%', @expression), @operator = SUBSTRING(@expression, @position, 1), @left = CONVERT(INT, LTRIM(RTRIM(LEFT(@expression, @position - 1)))), @right = CONVERT(INT, LTRIM(RTRIM(RIGHT(@expression, LEN(@expression) - (@position + 1))))), @result = CASE @operator WHEN '*' THEN @left * @right WHEN '/' THEN @left / @right WHEN '+' THEN @left + @right WHEN '-' THEN @left - @right END RETURN @resultENDGO;WITH [data] ([expression]) AS ( SELECT '1 + 5' UNION ALL SELECT '10 * 4' UNION ALL SELECT '15 / 3' UNION ALL SELECT '100 - 25' )SELECT [expression], [result] = [dbo].[SimpleMath]([expression])FROM [data]`
Post #1211149

 Permissions