How do I make an Insert into using dynamic SQL and run sp_executesql?

Asked

Viewed 224 times

0

I am trying to make an Insert using cursor and execute sp_executesql using variable, the first time it ran and did not return anything, I went to the table and had not added any record. Then I ran the second time and the duplicate key message appeared, but no record was added to the table.

Does anyone have any idea what might be happening and where I’m failing? Below follows the code I’m trying to do.

'''

    SET NOCOUNT ON;
    Begin
        DECLARE @COLUNA VARCHAR(100), @COLUNAS VARCHAR(MAX), @CLONAR NVARCHAR(MAX), @NovoId int, @PedidoId varchar(11), @vInsertInto NVARCHAR(MAX);

        --- Inicializar a variavel
        SET @COLUNAS    = ''
        SET @NovoId     = ''
        SET @CLONAR     = ''
        SET @PedidoId   = '1234'

        --sempre declare que o cursor é do tipo LOCAL FAST_FORWARD.
        --Local diz que é o scopo da execuçao e FAST_FORWARD significa que ele so vai pra frente.
        DECLARE CURCOLUNAS CURSOR LOCAL FAST_FORWARD FOR SELECT COLUMN_NAME
        FROM INFORMATION_SCHEMA.COLUMNS
        WHERE   TABLE_CATALOG   = 'banco'
                AND TABLE_SCHEMA= 'dbo'
                AND TABLE_NAME  = 'tabela'
        ORDER BY ORDINAL_POSITION
        OPEN CURCOLUNAS
            FETCH NEXT FROM CURCOLUNAS INTO @COLUNA
            WHILE @@FETCH_STATUS = 0
            BEGIN
                SET @COLUNAS = @COLUNAS + ',' + @COLUNA
                FETCH NEXT FROM CURCOLUNAS INTO @COLUNA --- O into nesta linha
            END

            SET @COLUNAS= Right(@COLUNAS, len(@COLUNAS)-1)
            --SET @CLONAR = N'SELECT '+@COLUNAS+' FROM tabela WHERE Id = '+@PedidoId;
            SET @vInsertInto = N'INSERT INTO tabela ('+@COLUNAS+') SELECT '+@COLUNAS+' FROM tabela WHERE Id = '+@PedidoId;

            SET IDENTITY_INSERT [banco].[dbo].[tabela] ON
            --EXECUTE sp_executesql @CLONAR;
            EXECUTE sp_executesql @vInsertInto;
            SET IDENTITY_INSERT [banco].[dbo].[tabela] OFF

        --SET @NovoId=SCOPE_IDENTITY()
        --RETURN  @NovoId
        CLOSE CURCOLUNAS;
        DEALLOCATE CURCOLUNAS;
    End

'''

  • 1

    Dude, if the second time you gave him a duplicate key, the first one must have worked... What may be happening is that this transaction is transacted, you are opening a transaction or this transaction is called within a?

  • It works right this, I switched to a table in a test db, and entered the records without problem.

  • @Danielmendes The Procedure is called in a system, it is not inside another process or something like that. I need to record a record and return the id of the new record but in my bank the new record does not appear. I do SELECT MAX(ID) of the table and it remains in the same id, as I don’t have much knowledge I don’t know where I might be missing.

  • @Ernestocasanova I’m glad it’s correct and you got it running. But with me being in the same place, I don’t have much experience so I don’t know where I might be going wrong. After running I do SELECT MAX(ID) of the table and does not change the id. I have to record a new record and then get the new ID and return it to the system that called Procedure. Can this be cache? A question now, as gave doubling of Chava whether will always be added a new record?

  • When I run the messages below appear: Message 2627, Level 14, Status 1, Line 1 Violation of PRIMARY KEY straint 'Pk_table'. Cannot Insert Duplicate key in Object 'dbo.Table'. The statement has been terminated. Message 16917, Level 16, Status 1, Line 43 Cursor is not open.

  • 1

    Guys I managed to make it work on my machine, but I had to make some adjustments: - After SET NOCOUNT ON; I added the SET CURSOR_CLOSE_ON_COMMIT ON; - I removed the two lines (SET IDENTITY_INSERT [bank].[dbo].[table] ON) - I put in place the following (BEGIN TRANSACTION;EXECUTE sp_executesql @vInsertInto;COMMIT TRANSACTION;) .

Show 1 more comment
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.