Search code examples
sql-server-2008t-sqlvariablescursor

Nested SQL cursor prints variable, but will not update


I'm using nested cursors to update the first column on every table of my Database, to populate data for an online reporting program.

when testing my cursors using a print statement, everything runs fine. When I switch to the update command, I get an error saying variable @table must be defined. Why does the variable only work for a print, and how can I make this work correctly?

declare @table varchar (30)
declare @Column varchar (30)

DECLARE [TABLE] CURSOR FOR SELECT TABLE_NAME FROM 
postfixing.INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE' order 
by table_name
OPEN [TABLE]
FETCH FROM [TABLE] INTO @TABLE
WHILE @@FETCH_STATUS=0
    BEGIN
    DECLARE [COLUMN] CURSOR FOR SELECT Top 1 Column_name FROM 
postfixing.INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME =@table order by 
column_name
    OPEN [COLUMN]
    FETCH FROM [COLUMN] INTO @COLUMN
    WHILE @@FETCH_STATUS=0
        BEGIN
        PRINT @TABLE+'   '+@COLUMN
        --UPDATE @TABLE SET @COLUMN=@COLUMN
        FETCH FROM [COLUMN] INTO @COLUMN
        END
    DEALLOCATE [COLUMN]
    FETCH FROM [TABLE] INTO @TABLE
END
DEALLOCATE [TABLE]

Solution

  • Well since you are only getting the first row you can eliminate the nested cursor and it should do what you want:

    declare @table varchar (30)
    declare @Column varchar (30)
    
    DECLARE [TABLE] CURSOR FOR SELECT TABLE_NAME FROM 
    postfixing.INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE' order 
    by table_name
    OPEN [TABLE]
    FETCH FROM [TABLE] INTO @TABLE
    WHILE @@FETCH_STATUS=0
        BEGIN
    
        SET @COLUMN = (SELECT Top 1 Column_name FROM 
    postfixing.INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME =@table order by 
    column_name)
    
        PRINT @TABLE+'   '+@COLUMN
        --UPDATE @TABLE SET @COLUMN=@COLUMN
    
    FETCH FROM [TABLE] INTO @TABLE
    END
    CLOSE [TABLE]
    DEALLOCATE [TABLE]