2013-07-25 34 views
0

我有表[合同]與列[id],[number]。我還有一些字符串格式的數字:'12342','23252','1256532'。我想要得到這樣的輸出。如果行存在或不存在,則顯示布爾

1535325 | no 
12342 | yes 
23252 | yes 
434574 | no 
1256532 | yes 

我當然可以這樣寫,讓我有行,但我怎麼能確定該行不存在,並得到上面的輸出:

SELECT [Id] 
     ,[Number] 
    FROM [Contracts] 
    where [Number] in 
    ('12342', '23252', '1256532') 

回答

1

你可以把值代入臨時表或表變量和做left join

declare @d table (Number varchar(10)) 
insert into @d values ('12342'), ('23252'), ('1256532'), ('xxxx') -- last one is not in Contracts 

SELECT c.[Id], c.[Number], case when d.Number is NULL then 'no' else 'yes' end [This Number from C is in D also] 
FROM [Contracts] c 
    left join @d d on d.Number = c.Number 

爲 「相反」 使用right join

SELECT c.[Id], d.[Number], case when c.Number is NULL then 'no' else 'yes' end [This Number from D is in C also] 
FROM [Contracts] c 
    right join @d d on d.Number = c.Number 
+0

謝謝,但我真的必須站在@d表,換句話說,如果@d表有行中不存在[數]我必須顯示號我改變腳本你的比喻,但它不工作 – Wachburn

+0

@Wachburn,請參閱編輯版本 –

相關問題