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



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source