Can I use CASE statement in a JOIN condition?

前端 未结 9 1771
庸人自扰
庸人自扰 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:40

    Instead, you simply JOIN to both tables, and in your SELECT clause, return data from the one that matches:

    I suggest you to go through this link Conditional Joins in SQL Server and T-SQL Case Statement in a JOIN ON Clause

    e.g.

        SELECT  *
    FROM    sys.indexes i
            JOIN sys.partitions p
                ON i.index_id = p.index_id 
            JOIN sys.allocation_units a
                ON a.container_id =
                CASE
                   WHEN a.type IN (1, 3)
                       THEN  p.hobt_id 
                   WHEN a.type IN (2)
                       THEN p.partition_id
                   END 
    

    Edit: As per comments.

    You can not specify the join condition as you are doing.. Check the query above that have no error. I have take out the common column up and the right column value will be evaluated on condition.

提交回复
热议问题