Question

This works:

dynSQL = "SELECT * FROM inventory WHERE vendor_item = '" + VendorItem + "' ";

...but this doesn't:

dynSQL = string.Format("SELECT * FROM inventory WHERE vendor_item = {0}", VendorItem);

The latter causes "Cannot find table 0"

This is another example of an attempt to pretty up the code knocking me right out of the saddle and onto the hardpan.

Is encasing the where clause arg in double quotes bookmarked by outer single quotes really the way to go? There has to be a better way (better than my "better way" (which is great except for the fact that it doesn't work)).

Was it helpful?

Solution

There is a better way. Whatever language you're using (you didn't specify--the string.Format part) undoubtedly supports parameterized SQL execution. Stop concatenating, and instead use parameters.

For example, in C# Entity Framework you would do something like this:

string esqlQuery = @"SELECT * FROM inventory WHERE vendor_item = @vendoritem";

using (EntityCommand cmd = new EntityCommand(esqlQuery, conn)) {
   EntityParameter vendoritem = new EntityParameter();
   vendoritem.ParameterName = "vendoritem";
   vendoritem.Value = VendorItem;

   cmd.Parameters.Add(vendoritem);
   // go on to execute it as shown in the above link
}

By creating a command and executing it, everything is done for you: parameter placement and formatting, including wrapping strings in single quotes and escaping single quotes or using "NULL" for null instead of "'NULL'".

One additional note is that your second code snippet has no single quotes around the token. But even if you get it "working", you're still susceptible to SQL injection. Best practice is to use parameterized SQL instead.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top