Results 1 to 5 of 5

Thread: Using cursor variable as a tablename

  1. #1
    Join Date
    May 2003
    Posts
    30

    Using cursor variable as a tablename

    I am currently using a cursor to scroll through sysobjects to extract table names and then extracting relevant column names from syscolumns.

    I then need to run the following script:

    declare Detail_Cursor cursor for
    select @colname, max(len(@colname)) from @table

    The message I receive is "must declare variable @table".

    Immediately prior to this script I printed out the result of @table which works fine so the variable obviously is declared and populated.

    Can anyone let me know what I'm doing wrong or how I can get the same result.

    Thanks

  2. #2
    Join Date
    Sep 2002
    Location
    Fantasy
    Posts
    4,254
    Why you need to use cursor? Try this

    select object_name(a.id), (select max(datalength(name)) from syscolumns where id =a.id)
    from sysobjects a where type='u' order by name

  3. #3
    Join Date
    Sep 2002
    Location
    Fantasy
    Posts
    4,254
    The previous statement gives the actual data length which is 2 bytes for one character since it is nvarchar.

    use this statement

    select object_name(a.id), (select max(len(name)) from syscolumns where id =a.id)
    from sysobjects a where type='u' order by name

  4. #4
    Join Date
    May 2003
    Posts
    30
    That's great, will try that now.

    Does this mean that you can't actually use the tablename from a variable?

  5. #5
    Join Date
    Sep 2002
    Location
    Fantasy
    Posts
    4,254
    declare @query varchar(2000
    set @query = 'select '+@colname+', max(len('+@colname+')) from '+@table
    exec (@query)

    or use sp_executesql

Posting Permissions

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