Case when a value is different to other value, SQL Server

后端 未结 4 1684
[愿得一人]
[愿得一人] 2021-02-18 13:57

I have this table structure for table prices:

CREATE TABLE prices
(
     id int, 
     priceFrom int, 
     priceUp int
);

INSERT INTO prices (id,          


        
4条回答
  •  无人及你
    2021-02-18 14:23

    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 .

提交回复
热议问题