Can I use CASE statement in a JOIN condition?

前端 未结 9 2023
庸人自扰
庸人自扰 2020-11-22 09:32

The following image is a part of Microsoft SQL Server 2008 R2 System Views. From the image we can see that the relationship between sys.partitions and sys

9条回答
  •  北荒
    北荒 (楼主)
    2020-11-22 09:47

    I think you need two case statements:

    SELECT  *
    FROM    sys.indexes i
        JOIN sys.partitions p
            ON i.index_id = p.index_id 
        JOIN sys.allocation_units a
            ON 
            -- left side of join on statement
                CASE
                   WHEN a.type IN (1, 3)
                       THEN a.container_id
                   WHEN a.type IN (2)
                       THEN a.container_id
                END 
            = 
            -- right side of join on statement
                CASE
                   WHEN a.type IN (1, 3)
                       THEN p.hobt_id
                   WHEN a.type IN (2)
                       THEN p.partition_id
                END             
    

    This is because:

    • the CASE statement returns a single value at the END
    • the ON statement compares two values
    • your CASE statement was doing the comparison inside of the CASE statement. I would guess that if you put your CASE statement in your SELECT you would get a boolean '1' or '0' indicating whether the CASE statement evaluated to True or False

提交回复
热议问题