2009-12-11 87 views
0

我试图想出一个使用Microsoft SQL Server的while循环的简单示例。 在这里我循环了所有以temp开头的表格。虽然在Microsoft SQL Server 2008中循环

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 

我的问题是:现在我已经通过表循环了,如何使用我用exec命令收集的信息? 换句话说,我可以将从exec命令返回的表存储到变量中吗?

回答

2

这里是我做这种工作的这些日子:

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 
+0

菲利普,这是一个很好的答案,谢谢! 我所有的SQL都属于你。 – 2009-12-11 16:50:03

2

如果我正确理解你的问题的话,当然,看here

只要插入到表中的VAR每次迭代,然后做什么就可以了之后。

2

如果你想用这种动态SQL来收集信息,那么你必须有一个地方来保存这些信息 - 临时表,永久表或表变量。然后,你应该能够做这样的事情:

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 
+0

哦,我也没多想前面做一个插入执行官!谢谢! – 2009-12-11 16:57:16