3


I have the following issue :
We have this query :

select price*hours as payment from table employees

Now, if the result of that multiplication it's 0, I'd like payment to be "x", not 0.
Translated in nonsql this would mean :

(price*hours) != 0 ? (price*hours) : "x"

Any ideas how could i implement this sql command ?
Thanks!

2
  • Why are you doing this on the SQL server as opposed to somewhere in code?
    – Roman
    Oct 20, 2010 at 11:00
  • I think I see the reason for my confusion now; note that x ?? y (null-coalescing) is a different operator to x ? y : z (conditional) Oct 20, 2010 at 11:01

6 Answers 6

8

Well, ?? would apply to NULL - in which case COALESCE or ISNULL - but you seem to mean 0 - in which case just:

SELECT ...blah...,
       CASE price*hours WHEN 0 THEN 'x' ELSE price*hours END AS [payment]
...more blah...

However, I would advise doing this as a UI concern rather than in the database. You may also want to think about how close to 0 it needs to be (floating point rounding etc).

4
  • Assuming that price and hours are numbers this statement will fail as SQL Server can't convert 'x' to a number. Oct 20, 2010 at 11:07
  • if pricehours comes out to half of x, or some other number between 0 and x, do you want that smaller number, or x? Is this about "we always charge a minimum of x, even for 0 hours" or "0 in the hours column is a special flag that means to charge x"? Because if its the latter I would really want to redesign that part - add a bit flag called ChargeMinimum and when that's set charge x instead of pricehours. Oct 20, 2010 at 11:08
  • @Xavier Poinas: "he might not have a presentation layer" -- I take that wager :)
    – onedaywhen
    Oct 20, 2010 at 11:09
  • @Barry - sure, add a CONVERT or whatever to fix that - but to be honest I'm not sure I want to encourage making it even worse ;p Oct 20, 2010 at 11:09
6
SELECT COALESCE(CAST(NULLIF(price * hours, 0) AS VARCHAR), 'x') AS payment_text
  FROM employees;

...but I agree with @Marc Gravell that this kind of formatting should be done in the 'front end'.

0
1

To tackle such problems, you can use the CASE statemnt

SELECT  payment = CASE
        WHEN price * hours = 0 THEN 'X'
        ELSE price * hours
        END
0
1
select payment =
  case price*hours
    when 0 THEN 'x'
    else price*hours
  end
from table employees
0
CASE
  WHEN somevar = 0 then "x"
  ELSE somevar
  END
0

Well you would have to convert the resulting number in to a string or it will fail as "x" isnt a number.

Maybe something like this:

Select Case 
       When Price * Hours = 0 Then "x" 
       Else Convert(varchar(50), (Price * Hours)) End as "Price"

From dbo.Table

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.