1、我之前写的没有优化的SQL语句:
declare @getmoney int
set @getmoney=0
select @getmoney=addscore from SignInRule where QMinDay=@countday //添加签到日志
set xact_abort on
begin tran //修改个人金币
declare @tempmoney bigint
select @tempmoney=WalletMoney from TUserInfo where UserID=@UserID
update TUserInfo set WalletMoney=@tempmoney+@getmoney where UserID=@UserID //修改个人元宝
commit tran
优化后的SQL语句:declare @getmoney int
select @getmoney=isnull(addscore,0) from SignInRule where QMinDay=@countday //添加签到日志
set xact_abort on
begin tran //修改个人金币
update TUserInfo set WalletMoney=WalletMoney+@getmoney where UserID=@UserID //修改个人元宝
commit tran
这里我用了isnull函数,这个函数对查找到字段值和没有查找到字段值都给赋了值,这样我们就少了变量的初始化工作;而且对语句的累加操作也做了优化处理
2、判断是否存在记录的exists语句注意
我想用exists判断记录是否存在的同时取得这条记录字段的值。所以做了如下书写
declare @tempmoney int
if exists(select @tempmoney=Money from TUsers where UserID=10007)
但是后来发现这条语句会出现判断错误,有记录的时候也会判断为假,后面改成如下判断就没问题
if exists(select * from TUsers where UserID=10007)
总结:exists只能判断记录是否存在不能同时做赋值处理
3、关于声明语句和赋值语句的书写
声明多个变量:
declare @money int,@age int,@name varchar(10)//这里声明不同类型的变量是对的
赋值语句:
set @money=123456,@age=543//这是不对的,不能同时对多个变量赋值
应该改成:
set @money=123456
set @age=543
4、内连接查询
--更新奖励到个人钱包
update A set A.WalletMoney=WalletMoney+T.GiveNum from TUserInfo A, (select B.UserID,C.GiveNum from TContestRecord_New B inner join Web_MatchAwardConfig C on C.TypeID=@SendTypeID and B.MatchID=@MatchID and B.RankNum=C.Rank) as T where A.UserID=T.UserID