如果行存在或不存在则显示bool

时间:2013-07-25 10:04:51

标签: tsql

我的表格[合约]包含列[id],[数字]。我也有一些字符串格式的数字:'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 个答案:

答案 0 :(得分: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