/***DB版本:SQL Server 2022***/
--切换数据库
use MyDatabase
--IF~ELSE
--查找账户ID为2的用户,如果存在,那么就在银行卡信息表内插入一条数据,如果不存在则在账户信息表和银行卡信息表内各插入一条
declare @AccountId int
if EXISTS(select AccountId from AccountInfo where AccountId = 2) --如果存在
begin
select @AccountId =(select AccountId from AccountInfo where AccountId = 2)
insert into BankCard(CardNo,AccountId,CardPwd,CardBalance,CardStatus) values('223456789612',@AccountId,'654321',764886.00,1)
end
else
begin
insert into AccountInfo(AccountCode,AccountPhone,RealName) values('22010219872019','13912875612',N'田中正敏')
select @AccountId =(select AccountId from AccountInfo where AccountId = 2)
insert into BankCard(CardNo,AccountId,CardPwd,CardBalance,CardStatus) values('223456789612',@AccountId,'654321',764886.00,1)
end
--CASE~WHEN~THEN
select CardNo,AccountId,CardBalance,
case
when CardBalance >= 3000000 then 'VIP'
else '普通'
end
from BankCard
結果: