求助:无法实现动态SQL传递动态表参数的解决方案
Alright, let's tackle this dynamic table parameter issue you're facing. Since you've stated you don't need to worry about SQL injection and just need the functionality working, here's exactly how to make this happen:
Solution for Dynamic Table Names in Dynamic SQL (C# + SSMS)
First, a quick heads-up: SQL parameters can't be used to replace table names (or column names)—they only work for value placeholders like numbers, strings, dates, etc. So to use a dynamic table name, you'll need to directly concatenate it into your SQL string.
Here's how to adjust your existing code to incorporate a dynamic table name, while keeping your existing parameterized Username value intact:
private void btnNext_Click(object sender, EventArgs e) { if (checkIntrotoPublicSpeaking.Checked || checkEffectiveOralCommunication.Checked || checkProfComm.Checked) { // 1. Define your dynamic table name (replace this with your actual source of the table name) string targetTableName = "YourDynamicTableName"; // Could come from a variable, checkbox text, etc. // 2. Keep your existing parameter setup for non-table values List<SqlParameter> sqlOralComm = new List<SqlParameter>(); sqlOralComm.Add(new SqlParameter("@Username", GlobalVariables.username)); // 3. Build the dynamic SQL string with the concatenated table name // Wrap the table name in square brackets if it has special characters/reserved words string dynamicSql = $"INSERT INTO [{targetTableName}] (Username, OtherColumn) VALUES (@Username, @OtherValue)"; // Adjust the SQL to match your actual operation (SELECT, UPDATE, etc.) // 4. Execute the dynamic SQL using (SqlConnection conn = new SqlConnection("YourConnectionStringHere")) { conn.Open(); using (SqlCommand cmd = new SqlCommand(dynamicSql, conn)) { cmd.Parameters.AddRange(sqlOralComm.ToArray()); // Add any other parameters you need for the query // cmd.Parameters.Add(new SqlParameter("@OtherValue", someValue)); cmd.ExecuteNonQuery(); // Use ExecuteReader/ExecuteScalar if you're fetching data } } } }
Quick Tips:
- If your table name might contain spaces, special characters, or SQL reserved words, always wrap it in square brackets
[]like in the example above to avoid syntax errors. - Even though you're not worried about injection right now, if you ever need to add safeguards later, you can validate the table name against a predefined list of allowed tables (e.g., check if
targetTableNameexists in a list of approved table names before using it).
内容的提问来源于stack exchange,提问作者tryingtotryhard




