Results 1 to 8 of 8

Thread: Adding variable to SELECT for CURSOR

  1. #1
    Join Date
    Oct 2002
    Posts
    2

    Adding variable to SELECT for CURSOR

    I'm trying to build a select statement for a CURSOR where part of the SQL statement is built using a variable.
    The following fails to parse:

    Declare Cursor1 Cursor
    For
    'select table_name from ' + @database + '.Information_Schema.Tables Where Table_Type = ''Base Table'' order by Table_Name'
    Open cursor1

    That doesn't work, I've also tried using an Execute() statement, no luck there either. Any ideas or suggestions are greatly appreciated.

  2. #2
    Join Date
    Sep 2002
    Location
    Fantasy
    Posts
    4,254
    store it in variable

    example

    declare @x varchar(8000)

    set @x = 'Declare Cursor1 Cursor For ' +
    'select table_name from ' + @database + '.Information_Schema.Tables Where Table_Type = ''Base Table'' order by Table_Name'

    exec (@x)

    Open cursor1

  3. #3
    Join Date
    Oct 2002
    Posts
    2

    Thank You

    That worked perfectly, Thank you.

  4. #4
    Join Date
    Mar 2003
    Posts
    383
    MAK: you are the real expert.
    How the idea of 'store declare xx cursor in variable' comes from? I just have the same puzzle like Kevin has, to loop the 30 around databases per server (around 80 servers) to defragment all the tables.
    I have made the cursors for database and then table and then index with this wonderful idea.

    thanks
    David

  5. #5
    Join Date
    Sep 2002
    Location
    Fantasy
    Posts
    4,254
    use this undocumented procedure

    sp_msforeachtable

  6. #6
    Join Date
    Sep 2002
    Location
    Fantasy
    Posts
    4,254
    sp_msforeachdb

    why cant you use Maintenance plan?

  7. #7
    Join Date
    Mar 2003
    Posts
    383
    To certain degree, I feel more control with the code and jobs I created. ex. one server with 700 databases, I could not run at batch, instead, need to run different time with different set of the databases with passing parameters to it.

    just by curiousity, is there any undoc proc for sp_msforeachsvr? (just kidding, otherwise I could run cross the 50 servers...)
    regards
    David

  8. #8
    Join Date
    Sep 2002
    Location
    Fantasy
    Posts
    4,254
    FYI. both msforeachdb and msforeachtable cannot be used together.

    refer my posting reg this

    http://forums.databasejournal.com/sh...=spmsforeachdb

Posting Permissions

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