SQL语句中的exists如何使用?如何搭配子查询
1、创建一个临时表,用于演示sqlserver语法中的exists使用方式
IF OBJECT_ID('tempdb..#tmp1') IS NOT NULL DROP TABLE #tmp1;
CREATE TABLE #tmp1(
Col1 varchar(50),
Col2 varchar(200)
);
2、往临时表中插入几行测试数据,用于演示exists使用
insert into #tmp1(Col1, Col2) values('Code1', '1');
insert into #tmp1(Col1, Col2) values('Code10', '2');
insert into #tmp1(Col1, Col2) values('Code100', '3');
3、查询临时表中的测试数据
select * from #tmp1;
4、如果在exists中查询的结果是NULL,最终exists返回的仍然是true。例如,下面的语句返回的就是整个表的结果
select * from #tmp1 where exists(select null);
5、使用子查询结合exists使用,当exists返回true的时候,就返回指定结果
select *
from #tmp1
where exists(select 1 from #tmp1 where Col2 = 2)
and Col1 = 'Code1'
6、使用子查询结合exists使用,当exists返回false的时候,就不会返回指定的结果。例如,将上面SQL子查询的Col2从等于2,改成等于20
select *
from #tmp1
where exists(select 1 from #tmp1 where Col2 = 20)
and Col1 = 'Code1'
7、在存储过程中,经常会使用exists判断条件是否成立,例如,判断临时表中是否存在记录
if exists(select 1 from #tmp1)
print '存在数据'
else
print '不存在数据'