Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 404
  • Last Modified:

Varchar Operator to Dynamic Formula

Hi Experts

I have a requirement for a user to enter two  numbers into a db and an operator, TSQL would do its magic and then return a result. I have the code below, but the problem  is that the operator is a varchar and building the formula is converting the output to a string - I need it to process the formula. Im thinking of sort sort of dyanamic SQL.

Below is my test code example - expected result is 200.

create TABLE  ##TEST
(
VALUE1 NUMERIC,
OPERATOR VARCHAR,
VALUE2 NUMERIC

)

INSERT INTO ##TEST VALUES ('100','+','100')


SELECT CONVERT(VARCHAR,VALUE1) + ' ' + OPERATOR + ' ' +  CONVERT(VARCHAR,VALUE2) FROM
(SELECT VALUE1, CASE OPERATOR
                                     WHEN '+' THEN '+'
                                    ELSE '-'
END AS OPERATOR, VALUE2 FROM ##TEST) AS A




DROP TABLE ##TEST
0
MrDavidThorn
Asked:
MrDavidThorn
  • 2
1 Solution
 
Ioannis ParaskevopoulosCommented:
Hi,

Please se the following:

create TABLE  ##TEST
(
VALUE1 NUMERIC,
OPERATOR VARCHAR,
VALUE2 NUMERIC

)

INSERT INTO ##TEST VALUES ('100','+','100')

DECLARE @SQL AS VARCHAR(500)--Here you probably want to change that. You need to consider how big are the numbers you are expecting

SET @SQL = 'SELECT ' + (
SELECT CONVERT(VARCHAR,VALUE1) + ' ' + OPERATOR + ' ' +  CONVERT(VARCHAR,VALUE2) FROM
(SELECT VALUE1, CASE OPERATOR 
                                     WHEN '+' THEN '+'
                                    ELSE '-' 
END AS OPERATOR, VALUE2 FROM ##TEST) AS A ) 

EXEC(@SQL)



DROP TABLE ##TEST

Open in new window


Giannis
0
 
MrDavidThornAuthor Commented:
I have worked out this way - only problem is that I can only hand one row at time, is there a way I can handle a record set.



create TABLE  ##TEST
(
VALUE1 NUMERIC,
OPERATOR VARCHAR,
VALUE2 NUMERIC

)

DECLARE @FORMULA varchar(max)

INSERT INTO ##TEST VALUES ('100','+','100')


SELECT @FORMULA =  (CONVERT(VARCHAR,VALUE1) + ' ' + OPERATOR + ' ' +  CONVERT(VARCHAR,VALUE2))  FROM
(SELECT VALUE1, CASE OPERATOR
                   WHEN '+' THEN '+'
                   ELSE '-'
END AS OPERATOR, VALUE2 FROM ##TEST) AS A

exec ('Select ' +  @FORMULA )


DROP TABLE ##TEST
0
 
Ioannis ParaskevopoulosCommented:
You may use a cursor. Tell me if you need an example of how to do that.

To be more precise you should provide some sample data in order to figure out what input and what outpt you expect.
0

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now