Skip to content

C# Is it safe to concatenate constant strings to form a SQL Query?

I need to change the table name dynamically based on specific conditions.

Is it safe to build my sql query the following way or am I prone to SQL Injection?

string GenerateSQL(string tableName) {
    return $"SELECT * FROM {tableName};";

const string tableName1 = "MyTable1"; 
const string tableName2 = "MyTable2";

string sql;
if (condition1) {
    sql = GenerateSQL(tableName1);
} else if (condition2)
    sql = GenerateSQL(tableName1);

To generalize, I want to build a parameterized sql query string by concatenating constant strings.



While this should not present any security problem as presented. There should not be any possibility for SQL injection since it does not involve any user input.

I would still argue for using parametrized queries whenever possible, because code change. There is a risk some future developer modifies the query to add a user injected parameter, or copies the example for some other purpose that does present a SQL injection vulnerability. Using parametrized queries everywhere would simplify your code guidelines and review.

But as with everything related to security, it does depend on your specific application, threat model and other factors that only you can determine.

8 People found this is helpful