Thom Andrews solves a problem:
Notice that the error line states line 2 not line 8, which is the line the
sys.sp_executesql
was called on. Knowing the line the error occured on within the dynamic batch is certainly important, but if you’re working with multiple dynamic batches you have no way of knowing which dynamic batch might have produced the error; was it the one executed on line 100? Line 200? Line 350?Solving this problem wasn’t wasn’t exactly simple, and it came with a couple of caveats.
Click through for the approach. As Thom mentions, it isn’t perfect, but it is reasonable and interesting.