Problem with CASE WHEN SQL-SERVER

Asked

Viewed 788 times

1

SELECT CASE WHEN VALOR > 0 THEN
VALOR ELSE
"Não tem"
END AS NOMECOLUNA
FROM BLABLABLA

I am having an error where it is not possible to convert "has not" to int.

The point is that I wanted it to return written that it does not have when the integer is 0...

2 answers

1


You can convert the numeric to VARCHAR since all the results of CASE must have the same type:

SELECT CASE
         WHEN VALOR > 0 THEN CAST(VALOR AS VARCHAR)
         ELSE 'Não tem'
       END AS NOMECOLUNA
  FROM BLABLABLA
  • Thanks man! That’s right! I was trying to put the cast in the validation, but I should put in the answer.

1

Within Case in SQL it is not possible to generate a column with numeric and text values as a single answer.

That is, in your code if the VALUE is greater than 0 it generates a numeric result and if less than 0 generates a text value.

I thought of 2 possible solutions:

1- Generate a separate column from the value column:

SELECT 
VALOR,
CASE WHEN VALOR > 0 THEN
"Com Valor" ELSE
"Não tem"
END AS NOMECOLUNA
FROM BLABLABLA

2-Generate output with text values for all cases (convert number to text):

SELECT CASE WHEN VALOR > 0 THEN
Put(VALOR, "numero de caracteres") ELSE
"Não tem"
END AS NOMECOLUNA
FROM BLABLABLA
  • I’m going to vote in favour of alternative paths, but the other answer was more correct.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.