SQL update 的原理

luoyefeng007 2013-07-23 10:53:28
以下SQL 执行在执行时使用了变量,请根据SQL update 的原理预测每一行在做Update 时变量的值!!
在解决此问题前,请了解以下 SQL update 的行原理

create table ta(物料 varchar(10),批号 varchar(10),库存数 int)
--/*--第一套测试数据
insert ta select 'aa','p01',5
union all select 'aa','p02',10
union all select 'bb','p01',20

create table tb(订单 int,物料 varchar(10),订货数 int)
--/*--第一套测试数据
insert tb select 1,'aa',11
union all select 1,'bb',10
union all select 2,'aa',2
union all select 3,'aa',1

go
SELECT ROW_NUMBER() OVER (ORDER BY b.物料,a.批号) AS fldID, b.订单,b.物料,a.批号,a.库存数,b.订货数,出库=cast(0 as int)
,未分配=cast(null as int),库存结余=cast(null as int),未配订单=cast(null as int),物料2=CAST(NULL AS NVARCHAR(10))
into #t
from ta a,tb b
where a.物料=b.物料
order by b.物料,a.批号,b.订单


SELECT * FROM ta ORDER BY 物料
SELECT * FROM tb ORDER BY 物料
SELECT * FROM #t ORDER BY 物料


--生成出库数据 --- 更新每一行时变量的值
declare @物料 varchar(10),@批号 varchar(10),@订单 int
declare @出库 int,@库存 int,@未分配 INT,@a INT
update #t SET
---@物料=null @批号=null,@物料='aa' @批号='p01'

@库存=case when 物料=@物料 then
case when 批号=@批号 then @库存 else @库存+库存数 end
else 库存数 end, -- 5,5,5,15,15,15,20

@出库=case when @库存>0 then
case when @物料=物料 then
case when isnull(@订单,订单)<=订单 then
case when @未分配>0 then
case when @库存<@未分配 then @库存 else @未分配 end
else case when @库存<订货数 then @库存 else 订货数 end end
else 0 end
else case when @库存<订货数 then @库存 else 订货数 end end
else 0 end, ----5,

--- 出库=@出库,

@未分配=case when @出库>0 then
case when @物料=物料 and @未分配>0 then @未分配-@出库 else 订货数-@出库 end
else @未分配 end, ---6,

@订单=case when @物料=物料 then
case when @出库>0 then
case when @未分配>0 then 订单 else 订单+1 end
else @订单 end
else case when @未分配>0 then 订单 else 订单+1 end end, ----1

@库存=@库存-@出库, ----0
出库=@出库, ----5

物料2=ISNULL(@物料,'')+ ISNULL(@批号,'')+ CAST(@库存 AS NVARCHAR(10)),

未分配=@未分配,库存结余=@库存,未配订单=@订单,
@物料=物料,@批号=批号





--显示更新结果
select 订单,物料,批号,出库 from #t
where 出库>0
order by 订单,物料,批号
go
--删除测试
drop table ta,tb
drop table #t
...全文
220 1 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
Andy__Huang 2013-07-23
  • 打赏
  • 举报
回复
做一个简单测试 create table tb(id1 int,id2 int,id3 int) insert into tb values(2,4,8) insert into tb values(10,20,25) select * from tb /* 2 4 8 10 20 25 */ declare @i int set @i=1 update tb set id1=id1+@i,@i=@i+1,id2=id2+@i,id3=id3+@i select * from tb drop table tb /* 4 6 10 13 23 28 */ 这样你就看得出来,每一条update语句使用的变量的值都是一样的

22,300

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧