0

I need to search a SQL table in C# for a value(filename). If it existed return TRUE and if not return FALSE and continue my code based on that.

This is what I have but it's not working:

SqlCommand cmdName = new SqlCommand("SELECT CASE WHEN EXISTS (SELECT * FROM [dbo].[Document] WHERE FileName = @NewFileName) THEN CAST (1 AS BIT) ELSE CAST (0 AS BIT) )", con);
{
 cmdName.Parameters.AddWithValue("@NewFileName", NewFileName);
 cmdName.ExecuteNonQuery();
}

Any suggestions?

The whole code is to prevent user from renaming a file to one that already existed in the table. So, if there is a better way to do it, I'd appreciate the help.

Horaciux
  • 6,322
  • 2
  • 22
  • 41
user3853986
  • 15
  • 1
  • 1
  • 8

2 Answers2

1

Using IF EXISTS is the fastest vay

string cmdText = @"IF EXISTS(SELECT 1 FROM [dbo].[Document] WHERE FileName = @NewFileName)
                   SELECT 1 ELSE SELECT 0"
SqlCommand cmdName = new SqlCommand(cmdText, con);
cmdName.Parameters.AddWithValue("@NewFileName", NewFileName);
int result = Convert.ToInt32(cmdName.ExecuteScalar());
if(result == 1)
   Console.WriteLine("File exists");

Of course you need to change the method called. ExecuteNonQuery is not appropriate for SELECT queries because the return value is the number of rows changed or modified by an action like INSERT/DELETE/UPDATE. Instead ExecuteScalar returns the first column of the first row of the query executed.

Steve
  • 213,761
  • 22
  • 232
  • 286
0

You can use like following, this has simplified SQL query.

SqlCommand cmdName = new SqlCommand("SELECT 1 FROM [dbo].[Document] WHERE FileName = @NewFileName", con);
cmdName.Parameters.AddWithValue("@NewFileName", NewFileName);
var result =  cmdName.ExecuteScalar();
if(result != null)
{
      // implies data exist
}

Or you can use this.

SqlCommand cmdName = new SqlCommand("SELECT 1 FROM [dbo].[Document] WHERE FileName = @NewFileName", con);
cmdName.Parameters.AddWithValue("@NewFileName", NewFileName);
SqlDataReader sdr = cmdName.ExecuteReader();
if (sdr.HasRows && sdr.Read())
{
          // implies data exist
}

// if you can check physically file is present in directory, then there is no DB call required. File check -- System.IO.File.Exists("PathToFile")

Arindam Nayak
  • 7,346
  • 4
  • 32
  • 48