SQL Server:从所有数据库获取所有视图

时间:2014-01-30 17:57:53

标签: sql sql-server tsql

实际上我能够获得包含某个表的所有数据库的列表:

SELECT name
FROM   sys.databases
WHERE  CASE
         WHEN state_desc = 'ONLINE' 
              THEN OBJECT_ID(QUOTENAME(name) + '.[dbo].[TABLE_NAME]', 'U')
       END IS NOT NULL 

但是现在我想做一些与视图类似的事情,以列出数据库中的所有视图。

你能用这种方法帮助我吗?

问候。

1 个答案:

答案 0 :(得分:2)

CREATE TABLE #v(d SYSNAME, v NVARCHAR(512));

DECLARE @sql NVARCHAR(MAX);
SET @sql = N'';

SELECT @sql = @sql + N'INSERT #v(d,v) 
  SELECT ''' + REPLACE(name, '''','''''') + ''',
  QUOTENAME(s.name) + ''.'' + QUOTENAME(v.name)
   FROM ' + QUOTENAME(name) + '.sys.views AS v
   INNER JOIN ' + QUOTENAME(name) + '.sys.schemas AS s
   ON v.[schema_id] = s.[schema_id]
   WHERE v.is_ms_shipped = 0;
'
FROM sys.databases
WHERE [state] = 0;

EXEC sp_executesql @sql;

SELECT [database] = d, [view] = v FROM #v ORDER BY d,v;

DROP TABLE #v;