每次选择插入并运行存储过程

时间:2017-12-02 16:58:58

标签: sql-server tsql

我有这样的查询:

INSERT INTO JETACE (TACE_KEY, TASK_KEY, CAET_KEY)
    SELECT @iTACE_KEY, TASK_KEY, CAET_KEY
    FROM JETACE
    WHERE TASK_KEY = @iTASK_KEY_CON

我唯一的问题是参数@iTACE_KEY - 它是唯一的(主键)并且生成如下:

EXEC @iTACE_KEY = sp_GETKEY 'JETACE', '0', '1', '9', @iUserId, @cTask='2'

我想为select语句中的每一行运行此句子,因此每个插入都将从表@iTACE_KEY中生成的TASK_KEY / CAET_KEYJETACE组合而来。这可能吗?

1 个答案:

答案 0 :(得分:0)

我用光标解决了问题:

DECLARE JETACE_01 cursor for
            SELECT CAET_KEY, TACE_SRT, TACE_STA
            FROM JETACE
            WHERE TASK_KEY = @iTASK_KEY_CON

            OPEN JETACE_01
            FETCH NEXT FROM JETACE_01 
            INTO @iCAET_KEY, @cTACE_SRT, @cTACE_STA


            WHILE @@FETCH_STATUS = 0
            begin

            EXEC @iTACE_KEY = sp_GETKEY 'JETACE', '0', '1', '9', @iUserId, @cTask='2'
            IF  (@@ERROR <> 0) OR (@iTACE_KEY < 0)
            BEGIN
                IF @cTask = '6'  
                    SELECT -61 TACE_KEY
                RETURN -61
            END

            INSERT INTO JETACE (TACE_KEY, TASK_KEY, CAET_KEY, TACE_SRT, TACE_STA, TACE_DAT, TACE_UAD, TACE_TAD)
            VALUES(@iTACE_KEY, @iTASK_KEY, @iCAET_KEY, @cTACE_SRT, @cTACE_STA, GETDATE(), @iUserId, GETDATE()) 


            FETCH NEXT FROM JETACE_01 
            INTO @iCAET_KEY, @cTACE_SRT, @cTACE_STA

            END


            CLOSE JETACE_01
            DEALLOCATE JETACE_01