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.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 Avoiding string concatenation

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?
Go to Top of Page

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2013-01-05 : 17:21:04
I'm not a C# programmer, so you'll need to fix this up. But here's a shot at it:

if(field1.CompareTo("A") == 0) someVar = "Field1"
else someVar = "Field2"

strSQL = "INSERT INTO Mytable (Code, inputdata) VALUES (?, ?)"

And then add a parameter for someVar.

Tara Kizer
Microsoft MVP for Windows Server System - SQL Server
http://weblogs.sqlteam.com/tarad/

Subscribe to my blog
Go to Top of Page

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.
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2013-01-06 : 10:16:35
i think query statement should be this

string strSQL = "INSERT INTO Mytable (Code, Datafield) VALUES ('1234', ?)"

if Code is integer you can dispense with ' inside

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page
   

- Advertisement -