检查视图是否存在

时间:2014-04-23 18:52:55

标签: c# sql-view sql-delete

我想通过我的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'
}

3 个答案:

答案 0 :(得分:2)

为什么不查询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;

答案 1 :(得分: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...
}

答案 2 :(得分:1)

只需要执行命令

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();
     }
 }