0

我在 SQL Server 中有一个存储过程。当我从 Delphi 执行它时,我收到一条死锁消息!

事务(进程 ID 60)在锁上死锁 | 具有另一个进程的通用等待对象资源,并已被选为死锁牺牲品

为了解决这种情况,我应该在下面的查询中进行哪些更改。我的存储过程没有参数。

ALTER PROCEDURE [dbo].[RepairStocks] 
AS
BEGIN
   SET NOCOUNT ON;

   drop table [dbo].[stocksss]

   select  
       Barkod, 
       sum(kolicina) as Kolicina, 
       Max(Kategorija) as Kategorija,
       Max(Artikal) as Artikal, 
       Max(Opis) as Opis, 
       Max(N_cena) as N_cena,
       Max(N_cena) * sum(kolicina) as N_Iznos, 
       Max(P_cena) as P_cena, 
       Max(P_Cena) * sum(kolicina) as P_Iznos, 
       Max(datum) as datum, 
       Max(Golemina) as Golemina
    into [dbo].[stocksss]
    from [dbo].[Stocks]
    group by Barkod

    drop table [dbo].[Stocks];

    select *
    into [dbo].[Stocks]
    from [dbo].[stocksss]   

END

任何帮助深表感谢...

编辑我的查询后

下面的查询适用于 SQL Server,但是当我从 Delphi 执行此操作时,我再次收到死锁消息。这是我的查询的样子:

ALTER PROCEDURE [dbo].[RepairStocks] 

AS
BEGIN

SET NOCOUNT ON;

SET TRANSACTION ISOLATION LEVEL SERIALIZABLE

BEGIN TRAN

select  
Barkod, 
sum(kolicina) as Kolicina, 
Max(Kategorija) as Kategorija,
Max(Artikal) as Artikal, 
Max(Opis) as Opis, 
Max(N_cena) as N_cena,
Max(N_cena) * sum(kolicina) as N_Iznos, 
Max(P_cena) as P_cena, 
Max(P_Cena) * sum(kolicina) as P_Iznos, 
Max(datum) as datum, 
Max(Golemina) as Golemina


into #tmp_stocks
from [dbo].[Stocks]
group by Barkod
--------------------------------
;
DROP TABLE [dbo].[Stocks]
;
--------------------------------


select *
into [dbo].[Stocks]
from #tmp_stocks with (nolock)
;
drop table #tmp_stocks
;

COMMIT TRAN

END

Delphi中,我使用以下代码执行命令:

RepairStocks.Close;
RepairStocks.SQL.Clear;
RepairStocks.SQL.Add('EXEC [dbo].[RepairStocks]');
RepairStocks.ExecSQL;
4

2 回答 2

4

您应该将其包装在可序列化的事务中

SET TRANSACTION ISOLATION LEVEL SERIALIZABLE
BEGIN TRAN
     ...
COMMIT TRAN

此外,您可以使用truncate而不是drop在表上清空它,并且您可以使用本地临时表 ( #Stocksss) 或表变量 ( @Stocksss) 而不是用户表

于 2013-09-21T17:28:14.530 回答
0

也许这不是最好的方法,但它对我有用,我得到了我应该得到的结果。当我在 Delphi 中执行此操作时,我也没有收到任何错误

@podiluska - 您的建议在 SQL Server Management Studio 中有效

ALTER PROCEDURE [dbo].[RepairStocks]
AS
BEGIN

begin tran

delete from stocksss


--insert from Stocks to Stocksss
INSERT INTO stocksss
select Barkod, 
sum(kolicina) as Kolicina, 
Max(Kategorija) as Kategorija,
Max(Artikal) as Artikal, 
Max(Opis) as Opis, 
Max(N_cena) as N_cena,
Max(N_cena) * sum(kolicina) as N_Iznos, 
Max(P_cena) as P_cena, 
Max(P_Cena) * sum(kolicina) as P_Iznos, 
Max(datum) as datum, 
Max(Golemina) as Golemina
from [dbo].[Stocks]
group by Barkod
;

----------------------------------------------------------

delete from Stocks

insert into Stocks
select * from stocksss
;

Commit Tran

END

谢谢!

于 2013-09-22T21:53:40.427 回答