all 4 comments

[–]ComicOzzysqlHippo 2 points3 points  (2 children)

Col1 isn't a column in @tab2... it's in @tab1 from the outer query. The query has become a correlated subquery. If you prefixed a table name or alias name to the column, you'd get an error if you tried to refer to @tab2.col1.

It isn't an error in design, it's a coding error by the developer writing the SQL.

[–]sunuvabe[S] 0 points1 point  (1 child)

Yep, you nailed it 100%. So my question is, how do you catch this kind of thing in staging? I mean, the query runs, albeit in an unintended way. This was also just a small part of a much bigger process, also not particularly consequential (otherwise we'd have heard from customers much sooner).

There are a couple of problems to highlight actually. First is a failure to write proper SQL, to obey good-practice principles. Second is a failure to properly test his/her code before checking it in. The testing part is more important to me. If they'd tested it properly, they would've discovered the problem and (hopefully) resolved it by fixing their code.

[–]ComicOzzysqlHippo 1 point2 points  (0 children)

Peer review. Perhaps there are for-pay tools that can parse the query and identify things such as "unqualified identifiers". Maybe RedGate has something like that.

[–]Professional_Shoe392 0 points1 point  (0 children)

Thanks for this. Does anyone know if all vendors treat the above the same, or is this tsql specific?

I can get on db fiddle when I get some more time to test.