2

如何删除特定架构下的所有视图。

例如:如果我在 db 中得到以下视图。

[dbo].[view1]
[dbo].[veiw2]
[dbo].[view3]
[myView].[view1]
[myView].[veiw2]
[myView].[view3]

我只想一次删除模式 myView 下的所有视图。

4

4 回答 4

2

试试这个:

select 'drop view ' + QUOTENAME(sc.name) + '.' + QUOTENAME(obj.name) + ';'
from sys.objects obj
INNER JOIN sys.schemas sc
ON sc.schema_id = obj.schema_id
where obj.type='V'
and sc.name = 'myView';
于 2012-05-21T04:53:11.143 回答
1

我有大量的视图(所以,只是将删除查询聚合到一个nvarchar(max)不起作用 - 查询被截断。)我想排除一些删除的视图。

在这个例子中,我想从每个模式中删除每个视图,但usr_*不以usr_test, usr_usr,和开头。usr_usr1usr_usr2usr_usr3

cursor使用是因为我不在乎几毫秒。这个视图清理查询是在集成测试之前使用的,它对速度不是很关键(但它表现得非常好)

declare drop_view_cursor cursor for
  select 'drop view ' + QUOTENAME(sys.schemas.name) + '.' + QUOTENAME(sys.views.name) + ';'
    from sys.views
    inner join sys.schemas on sys.schemas.schema_id = sys.views.schema_id
    where sys.schemas.schema_id in
    (
      select s.schema_id
        from sys.schemas as s
        where s.name like 'usr_%'
          and s.name not in ('usr_test', 'usr_usr', 'usr_usr1', 'usr_usr2', 'usr_usr3')
    )

declare @sql nvarchar(max)

open drop_view_cursor
fetch next from drop_view_cursor into @sql
while @@FETCH_STATUS = 0  
begin
  exec (@sql)
  fetch next from drop_view_cursor into @sql
end

close drop_view_cursor
deallocate drop_view_cursor
于 2021-06-09T14:28:11.960 回答
0

这考虑了 Schema,使用系统表,并输出到一个变量,然后可以执行。这样,您就不会遇到 Select 截断脚本的问题,因为 Select 和 Print 语句在它们可能返回的长度上受到限制。

以下在 SQL Server 2008 中运行:

DECLARE @DropViewCommand nVarChar(MAX) = ''
 SELECT @DropViewCommand = @DropViewCommand
                        + 'DROP VIEW '+ QUOTENAME(S.Name) + '.' + QUOTENAME(V.name) + '; '
   FROM sys.views   as V
   JOIN sys.schemas as S
     ON S.schema_id = V.schema_id
  WHERE S.name = 'dbo'--Selectively delete by Schema.  Comment out to delete all views.
PRINT @DropViewCommand--See the command used in dropping all views (will be truncated in Select/Print, but not when Executing).
EXEC (@DropViewCommand)
于 2013-03-14T07:55:27.643 回答
0

为那些寻找特定解决方案的人重新发布答案。将 DROP 视图代码放入 WHILE 循环中,如下所示:

DECLARE @name VARCHAR(128) 
DECLARE @SQL VARCHAR(254)
DECLARE @schema VARCHAR(128)

SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'V' AND category = 0 ORDER BY [name]) 
SELECT @schema = (SELECT TOP 1 schema_name(schema_id) FROM sys.views WHERE [name] = @name)

WHILE @name IS NOT NULL 
BEGIN 
    SELECT @SQL = 'DROP VIEW [' + @schema + '].[' + RTRIM(@name) +']' 
    EXEC (@SQL) 
    PRINT 'Dropped View: ' + @name 
    SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'V' AND category = 0 AND [name] > @name ORDER BY [name]) 
    SELECT @schema = (SELECT TOP 1 schema_name(schema_id) FROM sys.views WHERE [name] = @name)
END 
GO
于 2019-03-19T07:03:29.647 回答