【问题标题】:Stored procedure returns different result than the query in sql server存储过程返回的结果与 sql server 中的查询不同
【发布时间】:2015-03-06 01:55:20
【问题描述】:

我有一个存储过程,其中包含类似这样的代码,

if Exists(select * from sysobjects where name = 'tblProducts_Details' and xtype = 'U')
begin
  Drop table tblProducts_Details
End

select * into tblProducts_Details from tblProducts

alter table tblProducts_Details add gcode varchar(50)

update a set a.gcode = b.gcode from tblProducts_Details a
inner join GroupID_GCode_Mapping b
on a.Company = b.Company

alter table tblProducts_Details add group_code int

update a set a.group_code = b.local_group_code from tblProducts_Details a  
inner join Cache.dbo.Z_MAP_GroupID_CGCode_Mapping b
on a.gcode = b.gcode

alter table tblProducts_Details add groupname varchar(2000)

update a set a.groupname = g.name from tblProducts_Details a 
inner join tblProductsGroup g
on a.group_code = g.group_id

当我单独执行上述查询时,它返回了完美的结果。但是当我执行这个存储过程时,有时它会返回一个不同的结果集(有些行的值与期望的值不同)。

我不知道为什么。

【问题讨论】:

  • 为什么要为此使用持久表?您很可能遇到并发问题。您应该为此使用临时表。
  • 我还需要在另一个存储过程中使用这些表。这就是我不使用临时表的原因。
  • 但是如果有超过 1 个人运行你的 proc,他们就会互相踩踏。你知道你可以在一个 proc 中创建一个临时表,并且它将在第二个中可用(假设第二个 proc 是从第一个中调用的)?

标签: sql-server stored-procedures


【解决方案1】:

基础表(GroupID_GCode_Mapping、tblProductsGroup 和 Cache.dbo.Z_MAP_GroupID_CGCode_Mapping )必须在执行存储过程和检查结果之间发生变化。将整个东西包装在一个过程中没有什么不同。基于“缓存”数据库的更新可能需要很长时间,当您意识到 proc 完成时,数据已经发生变化。

【讨论】:

  • 实际上 Z_MAP_GroupID_CGCode_Mapping 表中没有任何修改。我只是用它来更新 tblProducts_Details 表中的 group_code。
  • 唯一被更新的表是 tblProducts_Detail。我认为正在发生的事情是您在时间 A 运行 proc。在随后的时间 B 更新基础源表,然后在时间 C 比较更新的内容时它们不匹配。要真正查看受影响的内容,请在更新语句中添加一个输出子句。然后,您可以准确地看到正在更新的内容。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-12-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-17
相关资源
最近更新 更多