2013-10-11 216 views
4

請參閱下面的DDL:CASE語句FROM子句

CREATE TABLE dbaddress 
(aid integer identity not null, link_id int, link_type char, primary key (aid)) 
CREATE TABLE dbDoorSupervisor 
(did integer identity not null, name varchar(30), primary key (did)) 
CREATE TABLE dbLicensee 
(lid integer identity not null, name varchar(30), primary key (lid)) 

INSERT INTO dbDoorSupervisor (name) values ('Ian') 
INSERT INTO dbLicensee (name) values ('Maria') 
INSERT INTO dbaddress (link_id, link_type) values (1,'D') 
INSERT INTO dbaddress (link_id, link_type) values (1,'L') 

我試圖去開門監事根據所提供的Address.AID名稱或許可。例如,如果輔助裝置1的WHERE子句中被提供,然後伊恩從門監表中返回,但是,如果輔助裝置2的WHERE子句然後瑪利亞從許可表中返回在被供給。

我知道你可以使用CASE語句在SELECT子句中,但你可以用它們在FROM子句即從地址到持牌人或地址加入到門主管根據所提供的援助?

+0

沒有,但你可以在兩個表中加入,然後用一種情況, SELECT只讀出每行的適當鏈接名稱。或者,您可以做兩個查詢,一個查找一個類型,另一個查找另一個類型,並將它們組合在一起。 –

+0

@JacobM,謝謝。我認爲答案是創建一個派生表,其中包含所有門主管和許可證持有人,我想你是暗示的。 – w0051977

回答

0

不無動態SQL,它有自己的一套問題。

如果你的數據庫是簡單的像這樣,只有2個左右的可能性,一個簡單的方法就是用成績手動加入都和處理,如:

select 
    a.aid 
    ,case a.link_type 
     when 'D' then ds.name 
     when 'L' then l.name 
    end [name] 
from 
    dbaddress a 
left join 
    dbDoorSupervisor ds on a.link_type = 'D' and a.link_id = ds.did 
left join 
    dbLicensee l on a.link_type = 'L' and a.link_id = l.lid 
+0

有一個在dbDoorSupervisor和dbLicensee沒有link_id列在OP模式:) –

+0

@RomanPekar更正。感謝您的支持。 –

2
select a.linkd_id, 
case when link_type = 'D' then d.name 
    when link_type = 'L' then l.name 
end as 'Name' 
from dbAddress a 
left join dbDoorSupervisor d on d.did = a.link_id 
left join dbLicensee l on l.lid = a.link_id 
4

可以在切換left outer join部分是這樣的:

select 
    isnull(d.name, l.name) as name 
from dbaddress as a 
    left outer join dbDoorSupervisor as d on d.did = a.link_id and a.link_type = 'D' 
    left outer join dbLicensee as l on l.lid = a.link_id and a.link_type = 'L' 

,還是要參加,並在case語句

01切換

如果你有一個以上的列顯示,您可以使用外適用,所以你不要」有重複的情況:

select 
    c.name, c.address, c.second_name 
from dbaddress as a 
    left outer join dbDoorSupervisor as d on d.did = a.link_id 
    left outer join dbLicensee as l on l.lid = a.link_id 
    outer apply (
     select d.name, d.second_name, d.address where a.link_type = 'D' union all 
     select l.name, l.second_name, l.address where a.link_type = 'L' 
    ) as c 
+0

作爲一個側面說明,如果有兩個以上的組合和你一起去了'isnull'路線,你既可以嵌套它們像'ISNULL(ds.name,ISNULL(dl.name,dx.name))'或去與[聚結](http://msdn.microsoft.com/en-us/library/ms190349.aspx) –

+0

@JoeEnos加入溶液爲多個列,它可以很容易地擴展爲多於一個的組合 –