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.
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.
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With