在sql server中时的请求不起作用

toe95027  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(343)

这是我的密码:

CREATE TABLE IF NOT EXISTS Artfacture 
(
     N int(6) unsigned NOT NULL,
     Code varchar(50) NOT NULL,
     Ht Numeric NOT NULL 
)

INSERT INTO Artfacture (N, Code, Ht) 
VALUES ('1', '1', '10'), ('1', '2', '20'),('1', '3', '30');

CREATE TABLE IF NOT EXISTS Facture 
(
     N int(6) unsigned NOT NULL,
     Ht Numeric NOT NULL 
)

INSERT INTO Facture (N, Ht) 
VALUES ('1', '60');

CREATE TABLE IF NOT EXISTS Article 
(
     Code varchar(50) NOT NULL, 
     Famille varchar(50) NOT NULL 
)

INSERT INTO Article (Code, Famille) 
VALUES ('1', 'F1'), ('2', 'F2'), ('3', 'F3');

CREATE TABLE IF NOT EXISTS Farticle 
(
     Designation varchar(50) NOT NULL, 
     Compte varchar(50) NOT NULL 
)

INSERT INTO Farticle (Designation, Compte)  
VALUES ('F1', '700000'), ('F2', '710000'), ('F3', '720000');

CREATE TABLE IF NOT EXISTS Ecritures 
(
     Compte varchar(50) NOT NULL, 
     Ht numeric NOT NULL  
)

我的请求是一个触发器,在表facture中添加一些新行时,它必须在ecritures中添加与artfacture行数相同的行

declare @piece as nvarchar(50), @code as nvarchar(50)
declare @rowCount int = 0, @currentRow int = 1
select @rowCount = count(*) from ArtFacture where N = @piece;

while (@currentRow <= @rowCount)
begin
    set @Code = (select code from ArtFacture where N = @piece)
    set @compte = (select Compte from Farticle where Designation = (select Famille from Article where code = @code))
    set @Ht = (select ht from ArtFacture where N = @piece)

    insert into Ecritures (Compte,Ht)
    values (@compte,@Ht)
end

我有一个错误,但我不知道在哪里?

suzh9iv8

suzh9iv81#

您犯了一个典型的错误,即试图编写过程性t-sql,而不是sql服务器优化的基于集的t-sql。
如果我遵循你的逻辑 insert 不再需要 while 回路:

insert into Ecritures (Compte, Ht)
select F.Compte, AF.Ht
from Artfracture AF
inner join Article A on A.Code = AF.Code
inner join Farticle F on F.Designation = A.Famille
where N = @piece;

如果你不想要复制品,加一个 group by :

insert into Ecritures (Compte, Ht)
select F.Compte, AF.Ht
from Artfracture AF
inner join Article A on A.Code = AF.Code
inner join Farticle F on F.Designation = A.Famille
where N = @piece
group by F.Compte, AF.Ht;

相关问题