使用我在本网站找到的样本,我成功编写了以下查询。 它运行良好,但是,我希望在结果中报告要查询的每个数据库的名称,在这两列之后。我所有的尝试都失败了。请帮忙。
DECLARE @sql varchar(max);
SELECT @sql = Coalesce(@sql + ' UNION ALL ', '') + 'SELECT column1, column2 FROM ' + QuoteName(name) + '.dbo.T_MyTable'
FROM sys.databases WHERE database_id > 4 AND state = 0
;
PRINT @sql
EXEC (@sql);
作为示例,以下因无效列名错误
而失败DECLARE @sql varchar(max);
SELECT @sql = Coalesce(@sql + ' UNION ALL ', '') + 'SELECT SoStoreNameTx, SoStoreNoTx, ' + quotename(name) + ' FROM ' + QuoteName(name) + '.dbo.T_SoStore'
FROM sys.databases WHERE database_id > 4 AND state = 0
;
PRINT @sql
EXEC (@sql);
答案 0 :(得分:1)
尝试以下代码
DECLARE @sql varchar(max);
SELECT @sql = Coalesce(@sql + ' UNION ALL ', '') + 'SELECT column1, column2, ''' + QuoteName(name)+ ''' as DBname FROM ' + QuoteName(name) + '.dbo.T_MyTable'
FROM sys.databases WHERE database_id > 4 AND state = 0
;
PRINT @sql
EXEC (@sql);