I have this table structure for table prices
:
CREATE TABLE prices
(
id int,
priceFrom int,
priceUp int
);
INSERT INTO prices (id,
You didn't provide the error, but by the format of your CASE EXPRESSION
I'm assuming it's throwing an error due to conversion.
You should use CAST to VARCHAR :
select pricefrom, priceup,
case
when pricefrom = 0 then ''
when priceFrom <> priceUp then CAST(priceFrom as varchar(10)) + ' - ' + CAST(priceUp as varchar(10))
when priceFrom = priceUp then CAST(priceFrom as varchar(10))
end as FinalPrice
from prices
I'm not sure about the first WHEN
, but you should know that :
usually the first condition of a CASE EXPRESSION
will determine the type of the column, so, if the first THEN
placing an integer, this column will be an integer.
since you are putting null value in it, I'm not sure which type the column will be evaluated to, so it can still throw an error, but you can give it a try :
when pricefrom = 0 then null
Note: Like @aakashpugta.0205 answer, using CONCAT()
the convertion is automatic, but you should know that CONCAT()
is available on SQL-Server only since 2012, so in older versions that won't work!
Let me also reffer you to an intersting article about CASE EXPRESSION secrets .