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.allocation_units
depends on the value of sys.allocation_units.type
. So to join them together I would write something similar to this:
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)
THEN a.container_id = p.hobt_id
WHEN a.type IN (2)
THEN a.container_id = p.partition_id
END
But the upper code gives a syntax error. I guess that's because of the CASE
statement.
Can anyone help to explain a little?
Thanks!
Add error message:
Msg 102, Level 15, State 1, Line 6 Incorrect syntax near '='.
Try this:
This seems nice
https://bytes.com/topic/sql-server/answers/881862-joining-different-tables-based-condition
I think you need two case statements:
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
Here I have compared the difference in two different result sets. Hope this might be helpful.
I took your example and edited it:
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.
Edit: As per comments.