Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
Author |
Topic |
parrot
Posting Yak Master
132 Posts |
Posted - 2013-01-05 : 13:52:59
|
In a previous topic it was emphasized not to concatenate strings when building an sql transaction. However, if the building of the string requires logic tests, what is the best way to avoid concatenation. For example, below is an instruction built using C# logic.string strSQL = "INSERT INTO Mytable (Code, inputdata) VALUES (";if(field1.CompareTo("A") == 0) strSQL += "Field1") else strSQL += "Field2");strSQL += ", ?)";string newsqlstring = strSQL; OleDbCommand myCommand = new OleDbCommand(newsqlstring, OleDbConn1);myCommand.Parameters.AddWithValue("@mydata", inputdata.Text); Is this safely avoiding string concatenation or is there another way to do it with logic involved in building the string? |
|
robvolk
Most Valuable Yak
15732 Posts |
Posted - 2013-01-05 : 17:20:40
|
What are Field1 and Field2? Are they variables in your program? Are they references to other columns in the same table being inserted? |
|
|
tkizer
Almighty SQL Goddess
38200 Posts |
|
parrot
Posting Yak Master
132 Posts |
Posted - 2013-01-05 : 17:43:13
|
newfield is a literal to be inserted based on the value of a inputted variable name called field1. So I think the logic would be coded as follows in C# using oledb commands to update the database names Code and Datafield into the database as follows: string newfield = "";if(field1.CompareTo("A") == 0) newfield = "Active";else if (field1.CompareTo("B") == 0) newfield = "Inactive";string strSQL = "INSERT INTO Mytable (Code, Datafield) VALUES ("1234", ?); OleDbCommand myCommand = new OleDbCommand(strSQL, OleDbConn1);myCommand.Parameters.AddWithValue("@mydata", newfield);Again I thank both of you for your reply. I think my question has been answered. |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2013-01-06 : 10:16:35
|
i think query statement should be thisstring strSQL = "INSERT INTO Mytable (Code, Datafield) VALUES ('1234', ?)"if Code is integer you can dispense with ' inside------------------------------------------------------------------------------------------------------SQL Server MVPhttp://visakhm.blogspot.com/ |
|
|
|
|
|
|
|