Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1242042
  • 博文数量: 510
  • 博客积分: 20296
  • 博客等级: 上将
  • 技术积分: 4680
  • 用 户 组: 普通用户
  • 注册时间: 2007-10-30 03:58
文章存档

2011年(13)

2010年(92)

2009年(242)

2008年(163)

我的朋友

分类: 数据库开发技术

2010-09-16 20:49:28

背景

    今天审核SQL语句,无意中看到2update写法很奇怪:

  1. update tb set weekNum = weekNum +dayNum where dayNum >0
  2. update tb set dayNum =0 where dayNum >0

     这样写法的原因主要是对SqlServer等数据库的不熟悉,感觉放在一起更新不大靠谱。其实完全可以合并在一起的。我们可以借助执行计划,看看实际的处理流程是怎么样的? 

  1. -- 切换到临时库,创建测试表
  2. use tempdb
  3. go
  4.  
  5. create table TestUpdate
  6. (id int not null
  7.  ,CurrNums int null
  8.  ,DayNums int null
  9.  ,MonthNums int null)
  10.  
  11. -- 插入测试数据
  12. insert into TestUpdate
  13. (id,CurrNums,DayNums,MonthNums)
  14. select 1,1,10,100
  15.     union all
  16. select 2,2,20,200
  17.     union all
  18. select 3,3,30,300
  19.     union all
  20. select 4,4,40,400
  21.     union all
  22. select 5,5,50,500
  23.  
  24. -- 检查数据
  25. select * from TestUpdate
  26. /*
  27.  
  28. id CurrNums DayNums MonthNums
  29. ----------- -------- ----------- --------------------
  30. 1 1 10 100
  31. 2 2 20 200
  32. 3 3 30 300
  33. 4 4 40 400
  34. 5 5 50 500
  35.  
  36. (5 行受影响)
  37. */
  38.           
  39. --查看更新语句的执行计划
  40. set showplan_text on
  41.  
  42. update TestUpdate
  43. set DayNums=DayNums+CurrNums
  44.     ,MonthNums=MonthNums+DayNums+CurrNums
  45.     ,CurrNums=0
  46.  
  47. --部分执行计划结果
  48.      |--Compute Scalar(DEFINE:( [Expr1004]=[tempdb].[dbo].[TestUpdate].[DayNums]+[tempdb].[dbo].[TestUpdate].[CurrNums]
  49.     [Expr1005]=[tempdb].[dbo].[TestUpdate].[MonthNums]+[tempdb].[dbo].[TestUpdate].[DayNums]))
  50.  |--Table Update(OBJECT:([tempdb].[dbo].[TestUpdate]), SET:(
  51.            [tempdb].[dbo].[TestUpdate].[DayNums] = [Expr1004]
  52.            [tempdb].[dbo].[TestUpdate].[MonthNums] = [Expr1005]
  53.            [tempdb].[dbo].[TestUpdate].[CurrNums] = [@1]))
  54.  
  55. --关闭设置并真正执行,查看结果
  56. set showplan_text OFF
  57.  
  58. update TestUpdate
  59. set DayNums=DayNums+CurrNums
  60.     ,MonthNums=MonthNums+DayNums+CurrNums
  61.     ,CurrNums=0
  62.    
  63. SELECT * FROM TestUpdate
  64.    
  65. /*
  66. id CurrNums DayNums MonthNums
  67. ----------- ----------- ----------- -----------
  68. 1 0 11 111
  69. 2 0 22 222
  70. 3 0 33 333
  71. 4 0 44 444
  72. 5 0 55 555
  73.  
  74. (5 row(s) affected)
  75.  
  76. */
    这里重点看下DEFINE部分和SET部分。中间定义了2个变量:[Expr1004]  [Expr1005],而CurrNums列则做了参数化处理[@1]3个字段的更新其实是并行在一次操作里面完成的,所以这里可以放心的把2个语句合并起来。

    最终结果里面的CurrNums列全部已经复位成0了。


【出自blog.csdn.net/jerrynet,转载请注明作者出处】

阅读(672) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~