SQL Server JOIN 與 CASE 語句:常見陷阱
在 SQL Server 2008 R2(及更高版本)中,嘗試直接在 CASE
條件中使用 JOIN
語句來定義連結條件可能會導致語法錯誤。 讓我們來看看為什麼以及如何解決這個問題。
考慮 sys.partitions
和 sys.allocation_units
之間的關係,其中連接取決於 sys.allocation_units.type
值。 一個天真的方法可能看起來像這樣:
<code class="language-sql">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</code>
這會導致錯誤「'='附近的語法不正確」。 問題是 CASE
表達式本身不會產生適合連接條件的布林值 (TRUE/FALSE) 結果。 相反,它會傳回 a.container_id = p.hobt_id
或 a.container_id = p.partition_id
,這兩者本身都不是有效的連接條件。
正確的方法:布林求值
要解決此問題,我們需要 CASE
表達式來產生布林值。 我們可以透過建立 CASE
語句來實現此目的,以傳回 1(表示 true)和 0(表示 false),然後將結果與 1 進行比較:
<code class="language-sql">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</code>
現在,僅當適當的條件(基於 CASE
)和相等性檢查(a.type
或 a.container_id = p.hobt_id
)都為真時,a.container_id = p.partition_id
語句的計算結果為 1。 然後,= 1
比較為 JOIN
條件提供必要的布林結果。 此修改後的查詢正確地連接了表。 此方法可確保 JOIN
條件計算為 true 或 false 值,使連線能夠如預期運作。
以上是SQL Server 的 JOIN 條件中可以使用 CASE 語句嗎?的詳細內容。更多資訊請關注PHP中文網其他相關文章!