我可以在JOIN条件下使用CASE语句吗?

以下图像是Microsoft SQL Server 2008 R2系统视图的一部分。 从图中我们可以看到sys.partitionssys.allocation_units之间的关系取决于sys.allocation_units的值。 所以为了将它们结合在一起,我会写下类似这样的东西:

 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声明。 任何人都可以帮忙解释一下吗?

谢谢!


添加错误消息:

消息102,级别15,状态1,行6'='附近语法不正确。

这是图像

CASEexpression式从子句的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进行比较。您的语句试图返回赋值或testing值的相等值,在CASE / THEN语句的上下文中都没有任何意义。 (如果BOOLEAN是一个数据types,那么平等的testing将是有意义的。)

相反,您只需join到两个表,并在您的SELECT子句中,从匹配的数据返回数据:

我build议你在JOIN ON子句中通过这个链接SQL Server中的条件连接和T-SQL Case语句

例如

  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 

编辑:根据意见。

你不能像你这样指定连接条件。检查上面的查询没有错误。 我已经拿出了共同的列,并在条件下评估右列值。

尝试这个:

 ...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) 

这看起来不错

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 

这里我比较了两个不同结果集的差异。 希望这可能会有所帮助。

 SELECT main.ColumnName, compare.Value PreviousValue, main.Value CurrentValue FROM ( SELECT 'Name' AS ColumnName, 'John' as Value UNION ALL SELECT 'UserName' AS ColumnName, 'jh001' as Value UNION ALL SELECT 'Department' AS ColumnName, 'HR' as Value UNION ALL SELECT 'Phone' AS ColumnName, NULL as Value UNION ALL SELECT 'DOB' AS ColumnName, '1993-01-01' as Value UNION ALL SELECT 'CreateDate' AS ColumnName, '2017-01-01' as Value UNION ALL SELECT 'IsActive' AS ColumnName, '1' as Value ) main INNER JOIN ( SELECT 'Name' AS ColumnName, 'Rahul' as Value UNION ALL SELECT 'UserName' AS ColumnName, 'rh001' as Value UNION ALL SELECT 'Department' AS ColumnName, 'HR' as Value UNION ALL SELECT 'Phone' AS ColumnName, '01722112233' as Value UNION ALL SELECT 'DOB' AS ColumnName, '1993-01-01' as Value UNION ALL SELECT 'CreateDate' AS ColumnName, '2017-01-01' as Value UNION ALL SELECT 'IsActive' AS ColumnName, '1' as Value ) compare ON main.ColumnName = compare.ColumnName AND CASE WHEN main.Value IS NULL AND compare.Value IS NULL THEN 0 WHEN main.Value IS NULL AND compare.Value IS NOT NULL THEN 1 WHEN main.Value IS NOT NULL AND compare.Value IS NULL THEN 1 WHEN main.Value <> compare.Value THEN 1 END = 1