Can I use CASE statement in a JOIN condition?

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

    This seems nice

    https://bytes.com/topic/sql-server/answers/881862-joining-different-tables-based-condition

    FROM YourMainTable
    LEFT JOIN AirportCity DepCity ON @TravelType = 'A' and DepFrom =  DepCity.Code
    LEFT JOIN AirportCity DepCity ON @TravelType = 'B' and SomeOtherColumn = SomeOtherColumnFromSomeOtherTable
    
    0 讨论(0)
  • 2020-11-22 09:50

    Try this:

    ...JOIN sys.allocation_units a ON 
      (a.type=2 AND a.container_id = p.partition_id)
      OR (a.type IN (1, 3) AND a.container_id = p.hobt_id)
    
    0 讨论(0)
  • 2020-11-22 09:52

    A CASE expression returns a value from the THEN portion of the clause. You could use it thusly:

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

    Note that you need to do something with the returned value, e.g. compare it to 1. Your statement attempted to return the value of an assignment or test for equality, neither of which make sense in the context of a CASE/THEN clause. (If BOOLEAN was a datatype then the test for equality would make sense.)

    0 讨论(0)
提交回复
热议问题