Answers:
对于SQL Server
IF EXISTS(select * FROM sys.views where name = '')
上面已经指定了许多方法,但是我最喜欢的方法之一却不见了。
GO
IF OBJECT_ID('nView', 'V') IS NOT NULL
DROP VIEW nView;
GO
nView
视图的名称在哪里
更新2017-03-25:正如@hanesjw建议删除存储过程使用P
而不是将其V
作为第二个参数OBJECT_ID
GO
IF OBJECT_ID( 'nProcedure', 'P' ) IS NOT NULL
DROP PROCEDURE dbo.sprocName;
GO
这是最可移植,最少侵入的方式:
select
count(*)
from
INFORMATION_SCHEMA.VIEWS
where
table_name = 'MyView'
and table_schema = 'MySchema'
编辑:这在SQL Server上确实有效,并且不需要您加入sys.schemas
即可获取视图的架构。如果一切都为dbo
,那么这并不重要,但是如果您充分利用了模式,则应牢记这一点。
每个RDBMS都有这种检查元数据的小方法,但information_schema
实际上是ANSI,我认为Oracle和显然的SQLite是唯一不以某种方式支持它的方法。
if exists (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[MyTable]') )
如果要检查所有现有视图的有效性和一致性,可以使用以下查询
declare @viewName sysname
declare @cmd sysname
DECLARE check_cursor CURSOR FOR
SELECT cast('['+SCHEMA_NAME(schema_id)+'].['+name+']' as sysname) AS viewname
FROM sys.views
OPEN check_cursor
FETCH NEXT FROM check_cursor
INTO @viewName
WHILE @@FETCH_STATUS = 0
BEGIN
set @cmd='select * from '+@viewName
begin try
exec (@cmd)
end try
begin catch
print 'Error: The view '+@viewName+' is corrupted .'
end catch
FETCH NEXT FROM check_cursor
INTO @viewName
END
CLOSE check_cursor;
DEALLOCATE check_cursor;
扩大凯文的答案。
private bool CustomViewExists(string viewName)
{
using (SalesPad.Data.DataConnection dc = yourconnection)
{
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(String.Format(@"IF EXISTS(select * FROM sys.views where name = '{0}')
Select 1
else
Select 0", viewName));
cmd.CommandType = CommandType.Text;
return Convert.ToBoolean(dc.ExecuteScalar(cmd));
}
}
您可以通过多种方式检查视图的可用性
对于SQL Server
使用sys.objects
IF EXISTS(
SELECT 1
FROM sys.objects
WHERE OBJECT_ID = OBJECT_ID('[schemaName].[ViewName]')
AND Type_Desc = 'VIEW'
)
BEGIN
PRINT 'View Exists'
END
使用系统对象
IF NOT EXISTS (
SELECT 1
FROM sysobjects
WHERE NAME = '[schemaName].[ViewName]'
AND xtype = 'V'
)
BEGIN
PRINT 'View Exists'
END
使用sys.views
IF EXISTS (
SELECT 1
FROM sys.views
WHERE OBJECT_ID = OBJECT_ID(N'[schemaName].[ViewName]')
)
BEGIN
PRINT 'View Exists'
END
使用INFORMATION_SCHEMA.VIEWS
IF EXISTS (
SELECT 1
FROM INFORMATION_SCHEMA.VIEWS
WHERE table_name = 'ViewName'
AND table_schema = 'schemaName'
)
BEGIN
PRINT 'View Exists'
END
使用OBJECT_ID
IF EXISTS(
SELECT OBJECT_ID('ViewName', 'V')
)
BEGIN
PRINT 'View Exists'
END
使用sys.sql_modules
IF EXISTS (
SELECT 1
FROM sys.sql_modules
WHERE OBJECT_ID = OBJECT_ID('[schemaName].[ViewName]')
)
BEGIN
PRINT 'View Exists'
END
sys.schema
这里。