I agree completely. String substitution in SQL is pretty stupid (it's not very good at string manipulation), non-parameterized SQL queries are very stupid as they're easily subjected to SQL Injection attacks, and both together (and there's a third language here as well, HTML) is just confusing as all hell. I'd split this up into only retrieving actual values from SQL Server using parameterized queries, writing a real JavaScript function that calls window.open, then writing formatted string code to generate the HTML to call the JavaScript function passing the parameters, and passing that through an HTML/XML entity encoding routine where that turns out to be necessary. As it is, that's an unmaintainable mess.
DoEvents: Generating unexpected recursion since 1991