SQL Server:迭代数据库中包含的所有表

时间:2014-01-03 12:58:37

标签: sql-server performance for-loop

我知道使用游标是一个坏主意,但我只是不知道如何解决这个问题。我想迭代我的表列表(select [table_name] from information_schema.tables)并在每个表上发出一个特定的select语句。

这是我的尝试:

DECLARE c CURSOR READ_ONLY FAST_FORWARD FOR
    SELECT [TABLE_NAME] 
    FROM INFORMATION_SCHEMA.TABLES 
    WHERE [TABLE_NAME] like 'TS%'

DECLARE @tableName char(7) 

OPEN c 

FETCH NEXT FROM c INTO @tableName 
WHILE (@@FETCH_STATUS = 0) 
BEGIN 
    -- which distinct ports has been used by inbound connections (listening sockets)?
    SELECT [protocol], [src_ip], [dst_ip], [src_port], [dst_port], [path] 
    FROM (SELECT *, ROW_NUMBER() over (partition by [dst_port], [protocol] order by [id]) as RowNumber 
             FROM @tableName -- <<<<<< THIS IS WHERE IT FAILS
             where [path] = 'RECEIVE') as a 
    WHERE a.RowNumber = 1 order by [dst_port];

    FETCH NEXT FROM c into @tableName
END
CLOSE c
DEALLOCATE c 

失败
  

必须声明表变量“@tableName”

什么是更好的方式在我的桌子上“迭代”像“foreach”?提前致谢

2 个答案:

答案 0 :(得分:1)

对于那种情况,我认为没有比你现在做的更好的表现方式。有一个未记录的存储过程sp_MSforeachtable,但我不推荐它,因为它不受微软的支持,并且会在你正在做的事情上做类似的过程。

答案 1 :(得分:1)

没有光标的解决方案 -

DECLARE @SQL NVARCHAR(MAX)
SELECT @SQL = STUFF((
    SELECT '

    SELECT [protocol], [src_ip], [dst_ip], [src_port], [dst_port], [path]
    FROM (
        SELECT *, rn = ROW_NUMBER() OVER (partition by dst_port, protocol ORDER BY id)
        FROM [' + SCHEMA_NAME([schema_id]) + '].[' + name + ']
        WHERE [path] = ''RECEIVE''
    ) a 
    WHERE a.rn = 1 
    ORDER BY dst_port;'
    FROM sys.objects
    WHERE [type] = 'U'
        AND name LIKE 'TS%'
    FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 2, '')

PRINT @SQL
EXEC sys.sp_executesql @SQL

输出 -

SELECT [protocol], [src_ip], [dst_ip], [src_port], [dst_port], [path]
FROM (
    SELECT *, rn = ROW_NUMBER() OVER (partition by dst_port, protocol ORDER BY id)
    FROM [dbo].[table1]
    WHERE [path] = 'RECEIVE'
) a 
WHERE a.rn = 1 
ORDER BY dst_port;

SELECT [protocol], [src_ip], [dst_ip], [src_port], [dst_port], [path]
FROM (
    SELECT *, rn = ROW_NUMBER() OVER (partition by dst_port, protocol ORDER BY id)
    FROM [dbo].[table2]
    WHERE [path] = 'RECEIVE'
) a 
WHERE a.rn = 1 
ORDER BY dst_port;