我有这个SQL查询
SqlCommand cmd = new SqlCommand("select distinct fld from client", con);
我可以使用变量
设置列名string str = "fld";
SqlCommand cmd = new SqlCommand("select distinct + str + from client", con);
答案 0 :(得分:4)
string str = "fld";
SqlCommand cmd = new SqlCommand(string.Format("select distinct {0} from client", str), con);
答案 1 :(得分:4)
最好在此处使用SQLCommand参数,如msdn中所述。这是为了防止SQL注入。
例如:
string commandText = "UPDATE Sales.Store SET Demographics = @demographics "
+ "WHERE CustomerID = @ID;";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(commandText, connection);
command.Parameters.Add("@ID", SqlDbType.Int);
command.Parameters["@ID"].Value = customerID;
// Use AddWithValue to assign Demographics.
// SQL Server will implicitly convert strings into XML.
command.Parameters.AddWithValue("@demographics", demoXml);
try
{
connection.Open();
Int32 rowsAffected = command.ExecuteNonQuery();
Console.WriteLine("RowsAffected: {0}", rowsAffected);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
但是,对于所选列,您仍必须使用动态sql,如此answer中的@marc_s所述。
正如@marc_s描述了他的解决方案:
var sqlCommandStatement = String.Format("select distinct {0} from client", "fld");
然后使用SQL Server中的sp_executesql
存储过程来执行该SQL命令(并根据需要指定其他参数)。