我有(用于测试目的)许多具有相同模式的dbs(=基本上相同的表和列)在sql server 2008 r2实例上.
我想要一个查询
SELECT COUNT(*) FROM CUSTOMERS
在实例上的所有DB上.我想要结果2列:
2 – COUNT(*)的值
例:
DBName // COUNT (*) TestDB1 // 4 MyDB // 5 etc...
注意:我认为CUSTOMERS表存在于所有的dbs(master除外).
解决方法
尝试这个 –
SET NOCOUNT ON; IF OBJECT_ID (N'tempdb.dbo.#temp') IS NOT NULL DROP TABLE #temp CREATE TABLE #temp ( [COUNT] INT,DB VARCHAR(50) ) DECLARE @TableName NVARCHAR(50) SELECT @TableName = '[dbo].[CUSTOMERS]' DECLARE @sql NVARCHAR(MAX) SELECT @sql = STUFF(( SELECT CHAR(13) + 'SELECT ''' + name + ''',COUNT(1) FROM [' + name + '].' + @TableName FROM sys.databases WHERE OBJECT_ID(name + '.' + @TableName) IS NOT NULL FOR XML PATH(''),TYPE).value('.','NVARCHAR(MAX)'),1,'') INSERT INTO #temp (DB,[COUNT]) EXEC sys.sp_executesql @sql SELECT * FROM #temp t
输出(例如,在AdventureWorks中) –
COUNT DB ----------- -------------------------------------------------- 19972 AdventureWorks2008R2 19975 AdventureWorks2012 19472 AdventureWorks2008R2_Live