Sample Header Ad - 728x90

Strange behavior with Quotename and substring

-1 votes
1 answer
422 views
I am seeing some behavior that I cannot figure out. We have a sproc that joins a bunch of tables and filters down some pipe-separated (|) values in a column. We cross apply a string splitter (I believe it is very much based on Jeff Moden's splitter) to separate the values. We then use the following to pull out the part we want to see based on the position of a tilde, concat some text to it and then wrap it in brackets. QUOTENAME( substring(tr.TableVar, 1, charindex('~', tr.TableVar) - 1) +'_someText' ) The issue that we started to see was an error "Invalid length parameter passed to the LEFT or SUBSTRING function." This would normally be pretty obvious to me: there's a value that does not contain a tilde. *However*, I have verified that every single record this query would return does, in fact, contain a tilde. This is both with an without any filtering done. I verified this with my eyeballs, with searching for any value that has 0 as the charindex value for the tilde, and a literal search for any record that doesn't contain a tilde (no records returned). What makes this weirder to me is that when I remove the QUOTENAME function, there is no error. I can also take the values and place them in a temp table, run the same select on those and it produces no error. I have also tried adding a replace to use search for a caret instead of a tilde (as below)... no error QUOTENAME( substring(tr.TableVar, 1, charindex('^', replace(tr.TableVar,'~','^')) - 1) +'_someText' ) I'm kind of grasping at straws at this point. Sure, we can just use the replace method but we would also like to know *why* we're now experiencing this error (this never happened before). Is there some kind of Unicode character issue with a tilde in the QUOTENAME function? Am I even on the right track? FWIW, we are on Azure SQL and are using collation SQL_Latin1_General_CP1_CI_AS. FYI and example (in fact the *only* value in this DB) looks like this after the split string (no quotes) 'DOG-1~3~_na_~'. Thanks in advance for your time. EDIT: I just went back and removed the joins to check the values without join conditions. There are indeed values that exist without the tilde. I do know that there are some cases when the engine isn't going to follow it's logical order (from, where, group by, etc) so it can effectively try to apply the substring before the filters. However, that leaves me wondering why using QUOTENAME makes that happen, and especially why using a replace doesn't throw the error; my thought would be that would cause the same issue. As always, thanks in advance
Asked by scarr030 (115 rep)
Oct 25, 2021, 01:16 PM
Last activity: Oct 25, 2021, 07:54 PM