SQL stored procedure works but with errors

我们两清 提交于 2019-12-12 04:02:36

问题


I have table with 3 primary keys : CODE_TARIF, UNITE, and MODE_LIV.

I write a stored procedure to copy and paste but with different MODE_LIV.

ex: if I already have 2 rows in table T_TARIF with MODE_LIV = 2, when I run this stored procedure with input MODE_LIV =3, I will have 4 rows .

ALTER PROCEDURE [dbo].[Copy_Tarif]
    -- Add the parameters for the stored procedure here
  @MODE_LIV int
AS
BEGIN
    DECLARE @CODE_TARIF varchar(15)
    DECLARE @ZONE int
    DECLARE @UNITE int
    DECLARE @LIBELLE varchar(30)

    DECLARE @TR_DEB int
    DECLARE @TR_FIN int
    DECLARE @MONTANT decimal(18,2)


    DECLARE tarif_cursor CURSOR FOR     
    SELECT CODE_TARIF, ZONE, UNITE, LIBELLE, TR_DEBUT, TR_FIN, MONTANT
    FROM T_TARIF

    OPEN tarif_cursor;

    FETCH NEXT FROM tarif_cursor 
    INTO  @CODE_TARIF, @ZONE, @UNITE, @LIBELLE,  @TR_DEB, @TR_FIN, @MONTANT;

    WHILE @@FETCH_STATUS = 0
    BEGIN
        INSERT INTO [T_TARIF]
           ([CODE_TARIF]
           ,[ZONE]
           ,[UNITE] 
           ,[MODE_LIV]         
           ,[LIBELLE]
           ,[TR_DEBUT]
           ,[TR_FIN]
           ,[MONTANT]

           )
     VALUES
           (@CODE_TARIF
           ,@ZONE
           ,@UNITE   
           ,@MODE_LIV       
           ,@LIBELLE
           ,@TR_DEB
           ,@TR_FIN
           ,@MONTANT

           )

        FETCH NEXT FROM tarif_cursor
        INTO  @CODE_TARIF, @ZONE, @UNITE, @LIBELLE,  @TR_DEB, @TR_FIN, @MONTANT;



    END
END

It works, but gives an error see Video : Strange Stored Procedure

Thanks you in advance, Stev


回答1:


Guessing...

You are using ISO cursor syntax. This defaults to not INSENSITIVE . Which means as you insert rows then when you FETCH you get rows you have just inserted etc etc.

From DECLARE CURSOR

DECLARE cursor_name [ INSENSITIVE ] [ SCROLL ] CURSOR

Defines a cursor that makes a temporary copy of the data to be used by the cursor. All requests to the cursor are answered from this temporary table in tempdb; therefore, modifications made to base tables are not reflected in the data returned by fetches made to this cursor, and this cursor does not allow modifications. When ISO syntax is used, if INSENSITIVE is omitted, committed deletes and updates made to the underlying tables (by any user) are reflected in subsequent fetches.

In any event, all you need is this: No need to loop

 INSERT INTO [T_TARIF]
       ([CODE_TARIF]
       ,[ZONE]
       ,[UNITE] 
       ,[MODE_LIV]         
       ,[LIBELLE]
       ,[TR_DEBUT]
       ,[TR_FIN]
       ,[MONTANT])
 SELECT 
       [CODE_TARIF]
       ,[ZONE]
       ,[UNITE] 
       ,@MODE_LIV       
       ,[LIBELLE]
       ,[TR_DEBUT]
       ,[TR_FIN]
       ,[MONTANT]
 FROM
      [T_TARIF]


来源:https://stackoverflow.com/questions/7848261/sql-stored-procedure-works-but-with-errors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!