0

I've been using a script that a coworker showed me to query against all of our databases. It starts with CREATE TABLE #tempTable and then I need to define all the columns. I was wondering if it was possible to not define the table and use SELECT * INTO instead.

Current Query:

    CREATE TABLE #tempTable(category nvarchar(50), eventType nvarchar(50), occurtime datetime);

    DECLARE @fixedname nvarchar(150);

    DECLARE dbCursor CURSOR FOR
        SELECT REPLACE(QUOTENAME(name),'''','''''')
           FROM master.sys.databases
           WHERE state_desc = 'ONLINE'
           AND HAS_DBACCESS(name) = 1
           AND name NOT IN ('master', 'msdb','model','tempdb');

    OPEN dbCursor
    FETCH NEXT FROM dbCursor INTO @fixedname;

    WHILE @@FETCH_STATUS = 0
    BEGIN
           EXEC ('USE ' + @fixedname + ';' +
                  'INSERT INTO #tempTable
                 SELECT
        DISTINCT UserChangeEvent.category [Category],
        UserChangeEvent.eventType [EventType],
        UserChangeEvent.occurTime[DateTime]
        
    FROM
        UserChangeEvent
    WHERE
         /* User Conditions */
         (
            (eventType LIKE ''Alarm'')      
         )

        AND UserChangeEvent.occurtime >= ''2021-01-01''
          
         ;');
           FETCH NEXT FROM dbCursor INTO @fixedname;
    END;

    CLOSE dbCURSOR
    DEALLOCATE dbCursor

    SELECT * FROM #tempTable

    --The following line can be commented out if you plan to do multiple queries within the 
    DROP TABLE #tempTable`

What I'm hoping might work:

    DECLARE @fixedname nvarchar(150);

    DECLARE dbCursor CURSOR FOR
        SELECT REPLACE(QUOTENAME(name),'''','''''')
           FROM master.sys.databases
           WHERE state_desc = 'ONLINE'
           AND HAS_DBACCESS(name) = 1
           AND name NOT IN ('master', 'msdb','model','tempdb');

    OPEN dbCursor
    FETCH NEXT FROM dbCursor INTO @fixedname;

    WHILE @@FETCH_STATUS = 0
    BEGIN
           EXEC ('USE ' + @fixedname + ';' +
                  'SELECT * INTO #tempTable   
         ;');
           FETCH NEXT FROM dbCursor INTO @fixedname;
    END;

    CLOSE dbCURSOR
    DEALLOCATE dbCursor

    SELECT * FROM #tempTable
    WHERE
         /* User Conditions */
         (
            (eventType LIKE ''Alarm'')      
         )

        AND UserChangeEvent.occurtime >= ''2021-01-01''

    --The following line can be commented out if you plan to do multiple queries within the 
    DROP TABLE #tempTable

I also read something that suggests I might not have to drop the table at the end since it's a temp table.

Jon C
  • 11
  • 1

0 Answers0