tags:

views:

103

answers:

6
+3  Q: 

?? operator in sql

Hi!
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!

+8  A: 

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).

Marc Gravell
+1 for suggesting to put this into the presentation layer.
Markus Winand
For what we know, he might not have a presentation layer...
Xavier Poinas
Assuming that `price` and `hours` are numbers this statement will fail as SQL Server can't convert 'x' to a number.
Barry
if price*hours 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 price*hours.
Kate Gregory
@Xavier Poinas: "he might not have a presentation layer" -- I take that wager :)
onedaywhen
@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
Marc Gravell
A: 
CASE
  WHEN somevar = 0 then "x"
  ELSE somevar
  END
Ignacio Vazquez-Abrams
+1  A: 

To tackle such problems, you can use the CASE statemnt

SELECT  payment = CASE
        WHEN price * hours = 0 THEN 'X'
        ELSE price * hours
        END
Anzeo
+1  A: 
select payment =
  case price*hours
    when 0 THEN 'x'
    else price*hours
  end
from table employees
Theofanis Pantelides
A: 

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
Barry
+6  A: 
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'.

onedaywhen
+1 I'm a big fan of using coalesce and nullif together!
Josh Smeaton