sql-server – SQL Server:迭代数据库中包含的所有表

我知道使用游标是一个坏主意,但我只是不知道如何解决这个问题.我想迭代我的表列表(从information_schema.tables中选择[table_name])并在每个表上发出一个特定的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 

这失败了

Must declare the table variable “@tableName”

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

最佳答案 对于那种情况,我认为没有比你已经做的更好的表现方式.有一个没有文档的存储过程
sp_MSforeachtable,但我不推荐它,因为它不受微软的支持,并且在幕后将会对你已经在做的事情进行类似的处理.

点赞