?? statement in sql


I have the following problem:
We have this request:

select price*hours as payment from table employees

Now, if the result of this multiplication is 0, I would like the payment to be "x" and not 0.
Translated to nonsql, this would mean:

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

Any ideas how I can implement this sql command?
Thank!

+3
source share
6 answers
SELECT COALESCE(CAST(NULLIF(price * hours, 0) AS VARCHAR), 'x') AS payment_text
  FROM employees;

... but I agree with @Marc Gravell that such formatting should be done in the "front end".

+6
source

Well, ??applicable to NULL- in this case COALESCEor ISNULL- but you seem to mean it 0- and in this case it’s simple:

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

, . , 0, ( ..).

+8

To solve such problems you can use statemnt CASE

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

Well, you have to convert the resulting number to a string or it won’t work, since “x” is not 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
0
source

Source: https://habr.com/ru/post/1770501/


All Articles