Results 1 to 3 of 3

Thread: T-SQL using cursor getting error, please help!

  1. #1
    Join Date
    Sep 2008
    Posts
    1

    T-SQL using cursor getting error, please help!

    I have the following code I found on this site and modified to loop through a table, pick up table names from this table, select from the table (using the value found) and update the table with the value found from the select.

    I added the row cnt so I will only do it once for a test. You can probably find the code on this site as I left the one line commented out that I didn't change from the sample I took.

    I get the following error:

    Msg 137, Level 15, State 2, Line 19
    Must declare the variable '@dbId'.

    It all looks right to me but am not an expert at coding TSQL, it's been some time!

    This is the code:

    declare @dbId nchar(100)
    declare @RowNum int

    declare dbList cursor for
    select table_name from dba.dbo.bigtables

    OPEN dbList
    FETCH NEXT FROM dbList
    INTO @dbId

    set @RowNum = 0
    WHILE @@FETCH_STATUS = 0
    BEGIN
    set @RowNum = @RowNum + 1
    -- print cast(@RowNum as char(1)) + ' ' + @dbId

    update dba.dbo.bigtables
    set xodus_update_before =
    (select max(xodus_update) from @dbId)
    where dba.dbo.bigtables.Table_Name = @dbId and
    @RowNum < 2

    FETCH NEXT FROM dbList
    INTO @dbId
    END
    CLOSE dbList
    DEALLOCATE dbList

    PS I need this for a production change tomorrow!! Thanks in advance.

  2. #2
    Join Date
    Sep 2002
    Posts
    5,938
    Try this:

    declare dbList cursor for
    select table_name from dba.dbo.bigtables

    declare @dbId nchar(100)
    declare @RowNum int

    OPEN dbList
    FETCH NEXT FROM dbList
    INTO @dbId

    ...

  3. #3
    Join Date
    Nov 2002
    Location
    New Jersey, USA
    Posts
    3,932
    Change dbid data type to char instead of nchar or modify WHERE clause for nchar N''

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •