检查视图是否存在
本文关键字:存在 是否 视图 检查 | 更新日期: 2023-09-27 17:59:46
我想通过windows窗体以编程方式检查视图是否存在,如果存在,则将其删除。我知道如何在SQL Server中做到这一点,但以前从未在C#中尝试过。我一直在使用这个语法,但不太清楚它的exat语法(或者它是否正确)。
using (var command1 = connection.CreateCommand())
{
command1.CommandText = "If Object_ID('ServerName.dbo.ViewName', 'V') IS NOT NULL DROP VIEW 'ServerName.dbo.ViewName'
}
为什么不查询sys.views
目录视图。下面的代码段。
bool exists;
var cmd = new OdbcCommand(
"select case when exists((select * from sys.views where name ='" +
viewName + "')) then 1 else 0 end");
exists = (int)cmd.ExecuteScalar() == 1;
如果将sql命令作为C#中的命令执行,为什么会有任何不同?
以下方法应该有效:
using (var command1 = connection.CreateCommand())
{
command1.CommandText = "IF EXISTS(select * from INFORMATION_SCHEMA.VIEWS where TABLE_SCHEMA = 'dbo' and TABLE_NAME = 'ViewName') DROP VIEW dbo.ViewName";
//todo: execute command, etc...
}
只需要执行命令
using (var sqlconnection = new SqlConnection())
{
using (var command = sqlconnection.CreateCommand())
{
command.CommandText = "If Object_ID('ServerName.dbo.ViewName', 'V') IS NOT NULL DROP VIEW 'ServerName.dbo.ViewName'";
command.ExecuteNonQuery();
}
}