我在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;
答案 0 :(得分:4)
您应该将其包装在可序列化的事务中
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE
BEGIN TRAN
...
COMMIT TRAN
此外,您可以在表上使用truncate
而不是drop
来清空它,并且可以使用本地临时表(#Stocksss
)或表变量( @Stocksss
)而不是用户表
答案 1 :(得分: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
谢谢!