Question

I want to programmatically through my windows form check if a view exists, and if it does, drop it. I know how to do this in SQL Server but have never attempted this in C# before. I was working with this syntax but can't quite figure out the exat syntax of it (or if it is even right).

using (var command1 = connection.CreateCommand())
{
  command1.CommandText = "If Object_ID('ServerName.dbo.ViewName', 'V') IS NOT NULL DROP VIEW 'ServerName.dbo.ViewName'
}
Was it helpful?

Solution 2

why would the sql command be any different if executed as a command from C# ?

the following should work:

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...
}

OTHER TIPS

Why don't you query the sys.views catalog view. Code snippet below.

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;

Just need to execute the command

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();
     }
 }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top