你能在SQL FROM语句中使用SQLParameter吗?

mor*_*pdx 3 c# sql parameters

我试图在C#中针对SQL Server数据库创建参数化查询.

码:

        query = new StringBuilder( "SELECT @fields FROM @tables");

        using(SqlConnection connection = new SqlConnection(connection))
        {
            SqlCommand command = new SqlCommand(query.ToString(), connection);
            command.Parameters.AddWithValue("@fields", fields.ToString());
            command.Parameters.AddWithValue("@tables", tables.ToString());

            try
            {
                connection.Open();
                Int32 rowsAffected = command.ExecuteNonQuery();
                Console.WriteLine("RowsAffected: {0}", rowsAffected);
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
Run Code Online (Sandbox Code Playgroud)

奇怪的部分是失败的消息"必须声明表变量"@ tables \".但是正如你所看到的,它已经被明确定义了.

所以我的问题是:

  1. 你能传递一个参数来定义FROM语句中的表列表吗?
  2. 如果可以,为什么这不起作用?

OMG*_*ies 7

SQL不支持参数化FROM子句.因此,您必须使用动态SQL,或者在将查询字符串提交到数据库之前创建/连接查询字符串.