0

我需要一次在表中添加多行。这些行有一些共同的字段值。我使用游标解决了我的问题,这是存储过程。

有没有人有更好的方法呢?

    USE [MyDataBase]
    GO


    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    ALTER PROCEDURE [dbo].[spAddDetailsBatch]
    (
    @IdOperTur UniqueIdentifier,
    @IdProd UniqueIdentifier,
    @Model Bit,
    @PrAd Decimal(18,2),
    @PrMe Decimal(18,2),
    @PoCo Decimal(5,2)
    )
    AS
    DECLARE @prpr_Id UniqueIdentifier
    DECLARE @IdCont UniqueIdentifier = NULL

    DECLARE CPr CURSOR FOR SELECT prpr_Id FROM trsx_PrPr WHERE (prod_Id = @IdProd)
    OPEN CPr

    FETCH NEXT FROM CPr INTO @prpr_Id
    WHILE @@Fetch_Status=0 BEGIN /*iterate through all records from cursor*/

     SET @IdCont = (SELECT cont_Id FROM trsx_Cont
                    WHERE  (prpr_Id = @prpr_Id) AND (optu_Id = @IdOperTur))

     IF @IdCont IS NULL
     BEGIN
      INSERT INTO trsx_Cont(cont_Id, prpr_Id, optu_Id, cont_Neto, cont_PrAd, cont_PrMe, cont_PoCo)
      VALUES (NEWID(), @prpr_Id, @IdOperTur, @Model, @PrAd, @PrMe, @PoCo)
     END

     FETCH NEXT FROM CPr INTO @prpr_Id
    END
   CLOSE CPr
   DEALLOCATE CPr
   RETURN

非常感谢。

4

1 回答 1

1

像这样的东西怎么样:

insert into trsx_Cont(cont_Id, prpr_id, optu_Id, cont_Neto, cont_PrAd, cont_PrMe, cont_PoCo)
select (newid(), trsx_PrPr.prpr_id, @IdOperTur, @Model, @PrAd, @PrMe, @PoCo)
from trsx_PrPr
where not exists(
    SELECT 1
    from trsx_Cont
    WHERE
        trsx_Cont.prpr_Id = trsx_PrPr.prpr_Id AND 
        trsx_Cont.optu_Id = @IdOperTur
) and
trsx_PrPr.prod_id = @IdProd

我没有对此进行测试,并且由于它有点复杂,因此它可能无法按原样工作,但是您应该能够理解。

于 2012-07-24T03:18:27.313 回答