exists子查詢


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:子查詢查不到結果,返回為真,子查詢查到結果返回為假


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM