2

I need to use the value of a variable as one of my fields in my SQL insert query that I am generating. In PHP I do this:

if($currency = "USD")
{
 $columntoinsert = "USD_Currency";
} 
else
{
 $columntoinsert = "";
}

Then in my SQL statement I would execute the query like so:

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

I want to do the same in C#. I have the following code to set the column I want to use

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

     }
  else
   {
      amountcolumn = "USD_Amount";
   }

But I can't execute my sql query in since trying to use amountcolumn in the query string generates an Invalid column name error which is expected. How can I use the variable in this manner:

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

Open to other alternatives. All help will be appreciated.

2
  • Parameterize the sql would be my suggestion Commented Oct 5, 2012 at 12:48
  • I don't think specifying columns in parameters will work to be used in the query. Commented Oct 5, 2012 at 13:07

2 Answers 2

8

Because the value for amountfield comes from your code logic, you can safely do this:

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

But never do things like this with strings coming from your users because that would make you open for SQL injection.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks dude. Worked like a charm. Learned something new today.
Actually the value does not come from the user directly but from the database and it was checked for any xss vulnerabilities or sql injection before saving.
3

Its

var amountfield = save_currency != "USD" ? "Amount" : "USD_Amount";

var sql = new sqlCommand("INSERT INTO Payments_TBL(column1,column2," 
+  amountcolumn + 
",column3,....)Values(@value,@value,@value)",new sqlConnection(conn));

OR

var sql = new sqlCommand(
                   String.Format("INSERT INTO Payments_TBL(column1,column2,  
                   {0},column3,....)Values(@value,@value,@value)", amountfield), 
                   new sqlConnection(conn));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.