I need to add multiple rows in a table at once. Those rows have some field values in common.
I solved my problem using a cursor and this is the stored proc.
Does anyone have a better way of doing it?
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
Thanks a lot.
How about something like this:
I haven’t tested this, and since it’s a little complex it may well not work as is, but you should be able to get the idea.