I have the following code to check if a SQL table exists:
using (var conn = new SqlConnection(SqlServerConnectionString))
{
conn.Open();
var selectQuery = $"SELECT count(*) FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = '{tableName}'";
var cmd = new SqlCommand(selectQuery, conn);
var reader = cmd.ExecuteReader();
while (reader.Read())
{
var count = reader.GetInt32(0);
return count > 0;
}
reader.Close();
conn.Close();
}
And it works fine. Is there a way to update this line to something more easily readable or easy to understand?
var count = reader.GetInt32(0);
2
Answers
There are several different ways to check if an table (or any other object) exists in the database.
This are very similar to search for every kind of object or just for tables:
or very short form this will return null if it does not exists or the object_id if it exists
If you just want your c# code shorter/cleaner than you could do this:
EDIT: as discussed in the comments I removed conn.Close()
using is just a short form for this to make sure that
conn
is disposed even if an exception occurs half way through the codeThis should work, and also fixes the nasty sql injection issue:
But you still have this line that is somewhat cryptic:
You could expand it into easier code like this:
Newer versions of C# can shorten this again with Pattern Matching:
Or more code, but maybe a little simpler to understand:
But I’m guessing if you don’t like the other code you won’t like pattern matching, either.