下图是 Microsoft SQL Server 2008 R2 系统 View 的一部分。从图中我们可以看到,sys.partitions 和 sys.allocation_units 之间的关系取决于 sys.allocation_units.type 的值。因此,为了将它们结合在一起,我会编写类似的内容:
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
但是上面的代码给出了语法错误。我猜这是因为 CASE
语句。
谁能帮忙解释一下吗?
添加错误消息:
Msg 102, Level 15, State 1, Line 6 Incorrect syntax near '='.
最佳答案
CASE
表达式从子句的 THEN
部分返回一个值。你可以这样使用它:
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
请注意,您需要对返回值执行一些操作,例如将其与 1 进行比较。您的语句尝试返回赋值或测试相等性的值,这两者在 CASE
/THEN
子句的上下文中都没有意义。 (如果 BOOLEAN
是一种数据类型,那么相等性测试就有意义。)
关于sql - 我可以在 JOIN 条件中使用 CASE 语句吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10256848/