2016-03-01 36 views
0

這是情況。我有兩個參數查詢: ITEM_CODE ITEM_TYPE如果在第一個表中找不到記錄,請從另一個表中選擇 - SQL Server 2012

的first_table包含: ITEM_CODE,Item_Characteristics

的second_table包含: ITEM_TYPE,Item_Characteristics

我的目標是讓item_characteristics。如果在第一個表中找不到特定的項目,我想使用Item_type從第二個表中獲取它們。

任何方式,這可以在一個單一的查詢?

我使用SQL Server 2012的

+0

看看這個[SO問題](http://stackoverflow.com/questions/18891453/mssql-select-from-another-table-if-no-results-from-the-first-table) – Icemanind

回答

2

一種方法是使用not exists

select t1.Item_Characteristics 
from t1 
where t1.item_code = @Item_Code 
union all 
select t2.Item_Characteristics 
from t2 
where t2.item_type = @Item_Type and 
     not exists (select 1 from t1 where t1.item_code = @Item_Code); 
2

您可以在案件Item_Code一個FULL JOINItem_Type嘗試是同一類型的:

這樣的
SELECT COALESCE(t1.Item_Characteristics, t2.Item_Characteristics) AS Item_Characteristics 
FROM table1 AS t1 
FULL JOIN table2 AS t2 
    ON t1.Item_Code = t2.Item_Type 
WHERE COALESCE(t1.Item_Code, t2. Item_Type) = @param 
+0

I理解答案(雖然不正確),但不是upvote。該問題顯式指定了兩個參數,而不是一個,並且沒有提示可以像這樣連接表。 –

+0

對不起,如果我不清楚。要查詢的參數可以是item_code或item_type,根據哪個人獲得item_characteristics。如果兩者都可以讓我得到item_characteristics,那麼我想用更具體的item_code。 – everydaylearn

+0

@everydaylearn然後看看Gordon Linoff的答案。 –

0

讓我知道這是否可行 -

select isnull(a.Item_Characteristics,b.item_type) 
from first_table as a 
left join second_table as b 
on a.Item_Characteristics = b.Item_Characteristics 
where a.Item_code = @itemcode and b.Item_type = @itemtype 
相關問題