2016-01-21 68 views
0

我不知道如何將if/casewhere exists語句合併。下面所有的領域都住在t_phoneSQL如果存在case語句

這是建立 - 存在即宣告

Declare @phone varchar(25) 

`select @phone = ....` 

我們需要說什麼電話臨時變量是一個customer_no如果給phone_type(從t_phone)存在對CUSTOMER_NO,與類型25使用與類型= 25,否則使用類型2

所以例如

phone_no   type   customer_no 
1234567890   2     4 
0987654321   25     4 
6537327345   2     8 
0123相關聯的phone_no

基於以上客戶4的例子,我們要設置@phone = 0987654321,因爲存在類型25,但對於客戶編號8,我們希望使用類型2,因爲沒有其他類型。

+0

你有什麼決定重要性的順序嗎?它是在一個表中還是在某個可用的地方定義的,25的優先級高於2? – gmiley

回答

1

如果2和25是唯一的類型,你可以做一個SELECT MAX()象下面這樣:

Select t.phone_no 
from t_phone t 
where t.type = (select max(ti.type) 
       from t_phone ti 
       where ti.customer_no=t.customer_no 
       and ti.type in (2,25)) 
+0

不幸的是,他們不是唯一的價值,但在這種情況下,我們只想看看2和25. – Elizabeth

+0

如果你添加到你的標準,這應該工作。我已更新答案 –

+0

我收到此錯誤消息:'子查詢返回多個值。當子查詢遵循=,!=,<, <= , >,> =或當子查詢用作表達式時,這是不允許的。' – Elizabeth

0

既然你只處理一個單一的客戶和你想要的值只有2型和25怎麼樣像這樣簡單。

select top 1 phone_no 
from t_phone 
where customer_no = @Customer 
order by 
case type when 25 then 2 
    when 2 then 1 
    else 0 end 
+0

這是拉一個完全不同/錯誤的電話號碼。 (已過期)我不確定爲什麼要這樣做。 – Elizabeth

+0

哎呀...順序應該有一個desc在最後。:) –

0
declare @phone varchar(25) 
select @phone = CASE t0.[type] 
       WHEN 25 THEN t1.phone_no 
       WHEN 2 then t2.phone_no    
       else 0 
       END 
from tbl t0 
left outer join tbl t1 on t1.type = 25 and t1.customer_no = t0.customer_no 
left outer join tbl t2 on t2.type = 2 and t2.customer_no = t0.customer_no 
+0

這似乎是在查看正確的數據元素 - 但發生了兩件事,一件需要更長時間才能運行,並且此代碼是許多程序調用的函數的一部分,這可能不是一件好事 - 但現在更大的問題 - 我得到的錯誤:'轉換varchar值'(414)444-4444 ext.4444'轉換爲數據類型int.'時轉換失敗' – Elizabeth

+0

請確保您的變量或數據類型不是int因爲字符(,), - ,.不是整數,而是字符。 – THROWAWAY3214

+0

t1和t2.phone字段是varchars - \t customer_no是整數,但其餘的數據都是varchars。我什至不知道它試圖轉換整數 – Elizabeth

1

你可以讓這個更容易實現保持通過引入表叫type_priority。這將有兩列:typepriority。對於type=25priority將是最高比如說10和type=2priority會說1

然後,當你選擇通過priority DESC與此表,以便加入並挑選top 1

select top 1 @phone = phone_no 
from t_phone ph 
join type_priority tp on tp.type = ph.type 
where customer_no = @Customer 
order by tp.priority desc 

該數據驅動的方法是更容易維護「怎麼你介紹其他類型,只是行適當priority添加到type_priority表和SQL語句繼續工作一樣。

請注意,對於type_priority表中缺少的types,將不會選擇記錄。所以,你需要確保它是最新的所有新引入的類型。

+0

我真的很喜歡這個想法,並且必須做更多關於實現它的研究 - 如果我們可以添加額外的臨時表,我必須在內部獲得批准。謝謝你的信息 – Elizabeth