views:

255

answers:

4

I'm trying to come up with a simple example of a while loop using Microsoft SQL Server. Here I'm looping through all the tables that begin with the word temp.

Declare @Object_ID int,@Name varchar(50)
set @Object_ID = 0
while exists (
    select * from 
    sys.tables
    where type = 'u' 
    and object_ID > @Object_ID 
    and Name like 'Temp%' 
) BEGIN
    select top 1 @Object_ID=Object_ID,@Name=Name
    from sys.tables
    where type = 'u' 
    and object_ID > @Object_ID 
    and Name like 'Temp%' 
    order by Object_ID
    exec('Select ''' + @Name + ''' as TableName,count(*) AS Counter from ' + @Name)
END

My problem is: now that I've looped through the tables, how do I use the information I've gathered with my exec command? In other words, can I stored the table that is returned from the exec command into a variable?

+2  A: 

You can store a temp table, similar to this example.

Jarrett Meyer
+2  A: 

If i understand your question correctly then sure, look here

Just insert into your table var for each iteration then do whatever on it afterwards.

Jammin
+1  A: 

If you want to gather information using dynamic SQL like that then you'll have to have a place to keep that information - a temp table, permanent table, or table variable. Then you should be able to do something like this:

Declare @Object_ID int,@Name varchar(50)
DECLARE
    @tbl TABLE (table_name SYSNAME, table_count INT)

set @Object_ID = 0
while exists (
    select * from 
    sys.tables
    where type = 'u' 
    and object_ID > @Object_ID 
    and Name like 'Temp%' 
) BEGIN
    select top 1 @Object_ID=Object_ID,@Name=Name
    from sys.tables
    where type = 'u' 
    and object_ID > @Object_ID 
    and Name like 'Temp%' 
    order by Object_ID

    INSERT INTO @tbl (table_name, table_count)
    exec('Select ''' + @Name + ''' as TableName,count(*) AS Counter from ' + @Name)
END

SELECT * FROM @tbl
Tom H.
Oh, I didn't think about doing an insert in front of the exec! Thank you!
cf_PhillipSenn
+1  A: 

Here is how I do this kind of task these days:

DECLARE
  @LoopId     int
 ,@Command    varchar(500)

DECLARE @List TABLE
 (
   TableName  sysname  not null
  ,LoopId     int      not null  identity(1,1)
 )

DECLARE @Results TABLE
 (
   TableName  sysname  not null
  ,Counter    int      not null
 )

--  Load with items you wish to review
INSERT @List (TableName)
 select name
  from sys.tables
  where Name like 'Temp%'
  order by Name desc

SET @LoopId = @@rowcount

--  Go through list and process each item
WHILE @LoopId > 0
 BEGIN
    SELECT @Command = 'SELECT ''' + TableName + ''' as TableName, count(*) as Counter from ' + TableName
     from @List
     where LoopId = @LoopId

    --  Load results in temp table
    INSERT @Results (TableName, Counter)
     execute (@Command)

    SET @LoopId = @LoopId - 1
 END

SELECT * from @Results
Philip Kelley
This was a great answer Philip, thank you!All my SQL are belong to you.
cf_PhillipSenn