我在SQL Server上有很多数据库(超过50个)。所有数据库都相同。每个数据库都有一个名为DBVersion的表。每个DBVersion都有一个列:“Version”,其类型为varchar。在此表中,始终存在一条记录。
如何循环遍历所有数据库,从表DBVersion中选择“Version”并在Microsft SQL Server Management studio中打印结果?
结果如下:
提前致谢。
答案 0 :(得分:2)
如果数据库位于同一个SQL-Server实例上,则可以使用sp_msforeachdb来迭代数据库
CREATE TABLE #tmp (DatabaseName VARCHAR(50), Version VARCHAR(200));
EXECUTE master.sys.sp_MSforeachdb '
USE [?];
IF EXISTS
( SELECT 1
FROM sys.tables
WHERE [Object_ID] = OBJECT_ID(N''dbo.DBVersion'')
)
BEGIN
INSERT #tmp (DatabaseName, TableName)
SELECT ''?'', [Version]
FROM dbo.DBVersion
END';
SELECT *
FROM #tmp;
DROP TABLE #tmp;
关于使用未记录的过程存在一些疑问,因此您可以使用游标重写它:
CREATE TABLE #tmp (DatabaseName VARCHAR(50), Version VARCHAR(200));
DECLARE DBCursor CURSOR LOCAL STATIC FORWARD_ONLY READ_ONLY
FOR
SELECT Name
FROM sys.databases;
OPEN DBCursor;
DECLARE @DBName VARCHAR(200) = '';
FETCH NEXT FROM DBCursor INTO @DBName;
WHILE @@FETCH_STATUS != 0
BEGIN
DECLARE @SQL NVARCHAR(MAX) = N'USE ' + QUOTENAME(@DBName) + '
IF EXISTS
( SELECT 1
FROM sys.tables
WHERE [Object_ID] = OBJECT_ID(N''dbo.DBVersion'')
)
BEGIN
INSERT #tmp (DatabaseName, TableName)
SELECT @DB, [Version]
FROM dbo.DBVersion
END';
EXECUTE SP_EXECUTESQL @SQL, N'@DB VARCHAR(200)', @DBName;
FETCH NEXT FROM DBCursor INTO @DBName;
END
CLOSE DBCursor;
DEALLOCATE DBCursor;
SELECT *
FROM #tmp;
DROP TABLE #tmp;
答案 1 :(得分:0)
这会对你有帮助吗?
SELECT 'Database1-Version:'+CAST(Version AS NVARCHAR) FROM Database1.schemaname.DBVersion UNION
SELECT 'Database2-Version:'+CAST(Version AS NVARCHAR) FROM Database2.schemaname.dbo.DBVersion UNION
....