How do I perform an IF…THEN in an SQL SELECT?

前端 未结 30 1784
梦如初夏
梦如初夏 2020-11-21 22:50

How do I perform an IF...THEN in an SQL SELECT statement?

For example:

SELECT IF(Obsolete = \'N\' OR InStock = \'Y\' ? 1 :          


        
30条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-21 23:29

    Use pure bit logic:

    DECLARE @Product TABLE (
        id INT PRIMARY KEY IDENTITY NOT NULL
       ,Obsolote CHAR(1)
       ,Instock CHAR(1)
    )
    
    INSERT INTO @Product ([Obsolote], [Instock])
        VALUES ('N', 'N'), ('N', 'Y'), ('Y', 'Y'), ('Y', 'N')
    
    ;
    WITH cte
    AS
    (
        SELECT
            'CheckIfInstock' = CAST(ISNULL(NULLIF(ISNULL(NULLIF(p.[Instock], 'Y'), 1), 'N'), 0) AS BIT)
           ,'CheckIfObsolote' = CAST(ISNULL(NULLIF(ISNULL(NULLIF(p.[Obsolote], 'N'), 0), 'Y'), 1) AS BIT)
           ,*
        FROM
            @Product AS p
    )
    SELECT
        'Salable' = c.[CheckIfInstock] & ~c.[CheckIfObsolote]
       ,*
    FROM
        [cte] c
    

    See working demo: if then without case in SQL Server.

    For start, you need to work out the value of true and false for selected conditions. Here comes two NULLIF:

    for true: ISNULL(NULLIF(p.[Instock], 'Y'), 1)
    for false: ISNULL(NULLIF(p.[Instock], 'N'), 0)
    

    combined together gives 1 or 0. Next use bitwise operators.

    It's the most WYSIWYG method.

提交回复
热议问题