Home Forums SQL Server 2005 T-SQL (SS2K5) TSQL Error using Cursor to loop through sysdatabases (Syntax Error) RE: TSQL Error using Cursor to loop through sysdatabases (Syntax Error)

  • ...and, if you have less that 250 or so databases, the following will beat the pants off your cursor 😉

    [font="Courier New"]--===== Declare local variables

    DECLARE @SQL VARCHAR(8000) --Holds the dynamic SQL

    --===== Build the dynamic SQL

    SELECT @SQL = ISNULL(@SQL+' UNION ALL'+CHAR(10),'')

    + 'SELECT u.tp_Login,''' + Name + ''' FROM [' + Name + ']..Sites s INNER JOIN ['

    + Name + ']..UserInfo u ON s.OwnerID=u.tp_ID'

    FROM Master.dbo.SysDatabases

    WHERE Name LIKE '%somefilter%'

    --===== Execute the dynamic SQL to get the result set

    EXEC (@SQL)[/font]

    --Jeff Moden


    RBAR is pronounced "ree-bar" and is a "Modenism" for Row-By-Agonizing-Row.
    First step towards the paradigm shift of writing Set Based code:
    ________Stop thinking about what you want to do to a ROW... think, instead, of what you want to do to a COLUMN.

    Change is inevitable... Change for the better is not.


    Helpful Links:
    How to post code problems
    How to Post Performance Problems
    Create a Tally Function (fnTally)