Home Forums SQL Server 7,2000 T-SQL Error/problems with using UNION in combo with CURSOR RE: Error/problems with using UNION in combo with CURSOR

  • Lynn Pettis (11/10/2009)


    EK rook (11/10/2009)


    Hey everbody,

    I have(or better yet tried to) create a cursor which acquires data from a table created from the union of two other tables in the same database, this is for all row that have column1 in table1 matching column2 in table2. Unfortunately the table formed doesn't seem to include the data gathered from the second select :unsure:

    My Code for doing this is as below:

    DECLARE CURS0 CURSOR FOR

    SELECT subqueryalias.col1, subqueryalias.col2, subqueryalias.col3, subqueryalias.col4, subqueryalias.col5, subqueryalias.col6

    FROM (

    SELECT col1, col2, col3 FROM Table1 WHERE (EXISTS (SELECT col5 FROM Table2 WHERE col1 =c5))

    UNION ALL

    SELECT col4, col5, col6 FROM Table2

    ) as subqueryalias

    WHERE subqueryalias.col1 = subqueryalias.col5

    This causes Error 207: Invalid columns names 'col4','col5','col6'.

    Col5 is flagged twice because its used in the where clause

    Once I get rid of the invalid columns; so the SELECT Statement is just SELECT subqueryalias.col1, subqueryalias.col2, subqueryalias.col3, the error disappears , but when i test the contents of the cursor, there is no data found.

    I've been working at this for practically the whole day, so any help with overcoming the problem would be greatly appreciated. Thanks in advanced 🙂

    First of all, there is no col4, col5, col6 returned from the subquery. There are only 3 columns; col1, col2, col3.

    You may want to take some time read a little more about UNION in BOL (MS SQL Server Books Online, the help system).

    It may help if you would fully explain what it is you are trying to accomplish. Also, is a cursor really needed? There may be a set-based solution to your problem that will work better and be more scalable as well.

    I'd also like to recommend that you read the first article I reference below in my signature block regarding asking for assistance. The more information you can provide, the better answers you will get in return.

    Ahh I wasn't aware the UNION only would used the columns just to return more rows. I must re think what how I am going to do this now . I will also look at the articles you referenced, thanks.