如何删除特定架构下的所有视图。
例如:如果我在db。中获得了以下视图。
[dbo].[view1]
[dbo].[veiw2]
[dbo].[view3]
[myView].[view1]
[myView].[veiw2]
[myView].[view3]
我只想一次删除模式myView下的所有视图。
答案 0 :(得分:1)
试试这个:
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';
答案 1 :(得分: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)
答案 2 :(得分:0)
为寻求特定解决方案的人重新发布answer。将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
答案 3 :(得分:0)
我有大量的视图(因此,仅将删除查询聚合到一个 nvarchar(max)
不起作用 - 查询被截断。)并且我想从删除中排除一些视图。
在此示例中,我想删除以 usr_*
开头的每个架构中的每个视图,但不删除 usr_test
、usr_usr
、usr_usr1
、usr_usr2
和 { {1}}。
usr_usr3
是因为我不关心速度。这个清理查询在集成测试之前使用,它不是速度关键(但它表现得很好)
cursor