3

I'm having some difficulty with the following SQL query:

SELECT
    SUM(ArTrnDetail.NetSalesValue) AS [Price],
    'ExecuteSubReport(813, 0, Job)' AS [LaborCost],
    'ExecuteSubReport(815, 0, Job)' AS [MaterialCost],
    'ExecuteSymbolicMath(LaborCost + MaterialCost)' AS [TotalCost],
    'ExecuteSymbolicMath(Price - (LaborCost + MaterialCost))' AS [Margin],
    CASE 
        WHEN SUM(ArTrnDetail.NetSalesValue) = 0 
            THEN 0
            ELSE 'ExecuteSymbolicMath(1 - (TotalCost / Price))'  <-- Where it's failing
    END AS [MarginPct]

The ExecuteSubReport and ExecuteSymbolicMath are company functions. The ExecuteSymbolicMath basically strips unwanted chars like $ and commas, does the math and returns the result as a string. The end result for the column being a decimal(2 places) between 0-1. When I try to run the query I get an error saying that it can't convert varchar to numeric. I've tried just about everything I can think of. I've tried replace, convert, cast, str.

Thank you very much for your help!

3
  • 2
    Hint: What's the type of the CASE expression? If it's numeric, how is 'ExecuteSymbolicMath(1-(TotalCost/Price))' going to be treated as a numeric value? Commented Jan 21, 2021 at 18:43
  • @PanagiotisKanavos - You're a genius! I'll post the answer. Commented Jan 21, 2021 at 18:51
  • 1
    You are passing in strings, not functions. I believe you want to remove the ' and ' around the expression you want SQL to parse as an expression Commented Jan 21, 2021 at 18:51

1 Answer 1

5

A SQL expression has exactly one type. A case expression is no different.

According to the rules of SQL, numbers trump strings, so SQL tries to convert a string to a number -- and that is what is happening.

Just use '0' instead of 0 in the case expression:

(CASE WHEN SUM(ArTrnDetail.NetSalesValue) = 0 
      THEN '0'
      ELSE 'ExecuteSymbolicMath(1-(TotalCost/Price))'  <-- Where it's failing
  END) AS [MarginPct]

Or, if you actually want a calculation, get rid of all the single quotes:

(CASE WHEN SUM(ArTrnDetail.NetSalesValue) = 0 
      THEN 0
      ELSE ExecuteSymbolicMath(1-(TotalCost/Price)) 
 END) AS [MarginPct]
Sign up to request clarification or add additional context in comments.

1 Comment

I just came to this conclusion. This fixed my problem. I'll give you credit. Thank you all!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.