SQL Server学习记录之语句优化

来源:互联网 发布:java poi jar 编辑:程序博客网 时间:2024/05/01 00:26
1、我之前写的没有优化的SQL语句:
declare @getmoney intset @getmoney=0select @getmoney=addscore from SignInRule where QMinDay=@countday //添加签到日志 set xact_abort on begin tran //修改个人金币 declare @tempmoney bigintselect @tempmoney=WalletMoney from TUserInfo where UserID=@UserIDupdate TUserInfo set WalletMoney=@tempmoney+@getmoney where UserID=@UserID //修改个人元宝 commit tran
优化后的SQL语句:
declare @getmoney intselect @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 intif 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=123456set @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
0 0
原创粉丝点击