传递C#变量并将其用作SQL语句查询中的列值

Max*_*axI 2 c# sql asp.net sql-server-2008

我需要使用变量的值作为我生成的SQL插入查询中的一个字段.在PHP中我这样做:

if($currency = "USD")
{
 $columntoinsert = "USD_Currency";
} 
else
{
 $columntoinsert = "";
}
Run Code Online (Sandbox Code Playgroud)

然后在我的SQL语句中,我会像这样执行查询:

$sqlinsertpayment = sqlsrv_query($connect,"INSERT INTO Payments_TBL(column1,column2,$columntoinsert,columnn)VALUES(????)",$params) or die("An error occurred trying to execute the statement");  
Run Code Online (Sandbox Code Playgroud)

我想在C#中做同样的事情.我有以下代码来设置我想要使用的列

var amountfield = "";
  if (save_currency != "USD")
    {
      amountcolumn = "Amount";

     }
  else
   {
      amountcolumn = "USD_Amount";
   }
Run Code Online (Sandbox Code Playgroud)

但我无法执行我的SQL查询,因为尝试amountcolumn在查询字符串中使用会产生Invalid column name预期的错误.如何以这种方式使用变量:

var sql = new sqlCommand("INSERT INTO Payments_TBL(column1,column2,myc#variablevaluehere,column3,....)Values(@value,@value,@value)",new sqlConnection(conn)); 
Run Code Online (Sandbox Code Playgroud)

对其他选择开放.所有帮助将不胜感激.

tpe*_*zek 8

因为值amountfield来自您的代码逻辑,所以您可以安全地执行此操作:

var sql = new sqlCommand(String.Format("INSERT INTO Payments_TBL(column1,column2,{0},column3,....)Values(@value,@value,@value)", amountcolumn),new sqlConnection(conn));
Run Code Online (Sandbox Code Playgroud)

但是永远不要使用来自用户的字符串来做这样的事情,因为这会让你打开SQL注入.