exists:
只注重子查询是否有返回行,如查有返回行结果为真,否则为假,并不适用子查询的结果,仅使用测试子查询是否有返回结果
语法:
if exists (子查询)
begin --如果有多条语句时需要适用begin end 语句如果只有一条语句时begin end可以省略
语句块
end
例子:
if exists(select * from sysdatabases where name='E_Market')
drop database E_Market
go
--exists子查询
--一次性购买“手机数码”产品的数量超过3个的,消费金额打8折
--根据已知项查询未知项
--【1】根据类别名称查询类别编号
use E_Market
go
select SortId from CommoditySort where SortName='手机数码'
--[2]根据1中类别的编号编号查询商品编号
select * from CommodityInfo where SortId=
(
select SortId from CommoditySort where SortName='手机数码'
)
--[3]根据2中得到的商品编号去查询订单表中的购买数量超过3个的用户信息
select * from OrderInfo where CommodityId in
(
select CommodityId from CommodityInfo where SortId=
(
select SortId from CommoditySort where SortName='手机数码'
)
) and Amount > 3
--[4]购买超过3个的用户的付款金额打8折
if exists(select * from OrderInfo where CommodityId in
(
select CommodityId from CommodityInfo where SortId=
(
select SortId from CommoditySort where SortName='手机数码'
)
) and Amount > 3)
begin
--对付款金额打八折
update OrderInfo set ParMoney=ParMoney*0.8
where CommodityId in
(
select CommodityId from OrderInfo where CommodityId in
(
select CommodityId from CommodityInfo where SortId=
(
select SortId from CommoditySort where SortName='手机数码'
)
) and Amount > 3
)
end
--通常会使用not exists对结果进行子查询的结果进行取反
--exists:子查询查到记录,结果为真否则结果为假
--notexists:子查询查不到结果,返回为真,子查询查到结果返回为假