I am trying to write an UPDATE query that can check for a null value in one of the fields. I have three conditions, two are mandatory, of three fields. itemCode and itemCheckDigit will always exist, itemSuffix is possibily Null.
There may be multiple records where itemCode and itemCheckDigit together are equal to other records, itemSuffix is the unquie identifier, only one instance will exist though where itemSuffix is Null and it will never be duplicated.
UPDATE item
SET itemImageFileName = ''' + @fileName + '''
WHERE (itemCode = ''' + @itemCode5 + ''') AND (itemCheckDigit = ''' + @itemCkDigit + ''') AND (itemSuffix IS NULL);
This is what I think I would like to do, but it is not working.
Your problem is that you are wrapping tick marks around your parameters in your statement so when it’s evaluated it looking for stuff from the item table where itemCode is ‘toy’ (note the single quotes)
The string concatenation you are doing is how one would, poorly, add parameters to their dynamic queries. Instead, take the tick marks out like so
To handle optional search parameters, this article by Bill Graziano is excellent: Using Dynamic SQL in Stored Procedures. I find that is strikes a good balance between avoiding the query recompilations of setting the recompile option on and avoiding table scans.
Please to enjoy this code. It create a temporary table to simulate your actual item table and loads it up with 8 rows of data. I declare some parameters which you most likely wont’ need to do as the ado.net library will do some of that magic for you.
Based on the values supplied for the first 3 parameters, you will get an equivalent match to a row in the table and will update the filename value. In my example, you will see the all NULL row will have the filename changed from f07.bar to f07.bar.updated.
The print statement is not required but I put it in there so that you can see the query that is built as an aid in understanding the pattern.
Before
after