SQL游标和存储过程

时间:2018-06-29 06:43:43

标签: sql-server tsql stored-procedures cursor

我有一个存储过程。订单表中有3个最大记录日期。我想一一读取ID并发送一个存储过程,但是会出现错误。

BEGIN TRAN

exec trn_siparis_insert 'Database',348

DECLARE @ID uniqueidentifier 

DECLARE SIPARIS CURSOR FOR

    Select id from TABLE.dbo.siparis  where kayit_tarihi = (SELECT MAX(kayit_tarihi) FROM TABLE.dbo.siparis );

    OPEN SIPARIS 

    FETCH NEXT FROM SIPARIS INTO @ID

    WHILE @@FETCH_STATUS =0
        BEGIN

            BEGIN TRAN

            exec trn_boyutlu_siparis_olustur @siparis_id=@ID, @TargetDb='Database'

            FETCH NEXT FROM SIPARIS INTO @ID

        END

    CLOSE SIPARIS 

    DEALLOCATE SIPARIS 

COMMIT TRAN 

1 个答案:

答案 0 :(得分:0)

BEGIN TRAN应该移至WHILE之前:

DECLARE @ID uniqueidentifier 

DECLARE SIPARIS CURSOR FOR

Select id from TABLE.dbo.siparis  where kayit_tarihi = (SELECT MAX(kayit_tarihi) FROM TABLE.dbo.siparis );

OPEN SIPARIS 

FETCH NEXT FROM SIPARIS INTO @ID

BEGIN TRAN

WHILE @@FETCH_STATUS =0
    BEGIN

        exec trn_boyutlu_siparis_olustur @siparis_id=@ID, @TargetDb='Database'

        FETCH NEXT FROM SIPARIS INTO @ID

    END

COMMIT TRAN 

CLOSE SIPARIS 

DEALLOCATE SIPARIS