Dynamic Query

  • Hello,I am trying to the result of a 'dynamic' Qry into a result Table. I should use an 'insert into ....values ....'

    But the number of colums on the qry are different, and I don't know how to get this done..

    Any Help is welcome...

    **-------Start of code--------------**

    DECLARE @TblName as varchar (50),

            @Cmd as varchar(200),

            @Row as integer

    -- This tablename should com as parameter to a SP

    SET @TblName = 'IF_INITIATESSCC'

    DECLARE Transfer_Cursor CURSOR FOR

    SELECT  ROW_NBR FROM TRANSFER_TABLE

    WHERE TABLENAME = @TblName

    AND CREATE_DATE > GETDATE() - 1

    ORDER BY CREATE_DATE DESC

    OPEN Transfer_Cursor

    FETCH NEXT FROM Transfer_Cursor

        INTO  @Row

    WHILE @@FETCH_STATUS = 0

    BEGIN

        SELECT @Cmd = 'SELECT *  FROM ' + @TblName + ' WHERE ROW_NBR = ' + CONVERT(varchar(20), @ROW)

        print @Cmd -- debug only

        EXEC (@Cmd)

        FETCH NEXT FROM Transfer_Cursor

                INTO  @Row

    END

    CLOSE Transfer_Cursor

    DEALLOCATE Transfer_Cursor

    **--------End of code -----------**

  • This cannot be done that way... You'd have to code the select statement of the cursor in dynamic sql too.

    What problem are you trying to solve?

  • One thing that can be done is a "SELECT... INTO..."  You would need to make sure that you dropped the table when finished as you cannot create a table with the same name during the same connection.

    EXAMPLE: 'SELECT * INTO ' + @NewTable + ' FROM ' + @Tbl + ' WHERE ' + etc...

    Thanks

    Greg

Viewing 3 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic. Login to reply