Help with CASE

  • Hi,

    Is it possible to do as follows:

    If Column1 = 0 then instead select the value from column2?

    Like this:

    SELECT CASE [Unit cost]

    WHEN 0 THEN [Logistic Unit price]

    END

    FROM blablabla

    or like this perhaps:

    SELECT 'UnitCost' = CASE

    WHEN [Unit cost] = 0 THEN [Logistic Unit price]

    END

    FROM blablabla

  • Yes, you can do it balalalalala

  • My problem is, that in this specific query the value is Null when it has to choose column2... (and the value is not null ;-))

  • Ahh... Got it working.. The problem was of course that I did not have an ELSE ... When the value <> 0 then Colounm1. 🙂

  • An alternative to CASE: -

    --Build some test data since you didn't supply any

    DECLARE @blablabla AS TABLE (UnitCost MONEY, UnitPrice MONEY)

    INSERT INTO @blablabla

    SELECT 0, 1.50

    UNION ALL SELECT 1.12, 1.45

    UNION ALL SELECT 1.53, 0

    UNION ALL SELECT 0, 0.15

    --Now the query

    SELECT ISNULL(NULLIF(UnitCost,0),UnitPrice)

    FROM @blablabla


    Forever trying to learn
    My blog - http://www.cadavre.co.uk/
    For better, quicker answers on T-SQL questions, click on the following...http://www.sqlservercentral.com/articles/Best+Practices/61537/
    For better, quicker answers on SQL Server performance related questions, click on the following...http://www.sqlservercentral.com/articles/SQLServerCentral/66909/

  • Well that was even better...

  • agh100 (5/5/2011)


    Well that was even better...

    Well, that depends 😉

    Best bet is to run some tests on your own data, or knock-up some test data to play with.

    Try this to get you started -

    DECLARE @blablabla AS TABLE (UnitCost MONEY, UnitPrice MONEY)

    INSERT INTO @blablabla

    SELECT TOP 1000000

    CASE WHEN RAND(CHECKSUM(NEWID())) * 10 < 5

    THEN 0

    ELSE ROUND(RAND(CHECKSUM(NEWID())) * 100.00,2) END,

    ROUND(RAND(CHECKSUM(NEWID())) * 100.00,2)

    FROM sys.all_columns ac1

    CROSS JOIN sys.all_columns ac2

    --Check Data

    SELECT * FROM @blablabla


    Forever trying to learn
    My blog - http://www.cadavre.co.uk/
    For better, quicker answers on T-SQL questions, click on the following...http://www.sqlservercentral.com/articles/Best+Practices/61537/
    For better, quicker answers on SQL Server performance related questions, click on the following...http://www.sqlservercentral.com/articles/SQLServerCentral/66909/

Viewing 7 posts - 1 through 7 (of 7 total)

You must be logged in to reply to this topic. Login to reply