有没有办法引用在“sp_msforeachdb”循环内运行的“sp_MSforeachtable”循环内的表?
例如,在以下查询中,“?” 总是引用数据库:
DECLARE @cmd VARCHAR(8000);
SET @cmd = 'USE ?; EXEC sp_MSforeachtable @command1="select db_name = DB_NAME(), db_foreach = ''?'', tb_foreach = ''?'' "'
EXEC sp_msforeachdb @command1 =@cmd
导致:
db_name db_forearch tb_foreach
ServerMonitor master master
我想要类似的东西:
db_name db_forearch tb_foreach
ServerMonitor master <TABLE_NAME>
我应该改变什么?
解决了。按照 Sean 的建议,我使用了我的 ow 光标。但是 Ben Thul 建议的 @replacechar 解决方案正是我想要的。
DECLARE @cmd VARCHAR(8000);
SET @cmd = 'USE ^; EXEC sp_MSforeachtable @command1="select db_name = DB_NAME(), db_foreach = ''^'', tb_foreach = ''?'' "'
EXEC sp_msforeachdb @command1 =@cmd, @replacechar = '^'