I recently had a need to find a way of obtaining just the column names returned by a SQL Server Query; the query in question is ad-hoc and entered into an application by the user (in this case my application is a WPF desktop application, and the query is Microsoft T-SQL).
One quick and simple way of obtaining the column names would be to execute the query; I will not go into the details of why executing arbitrary SQL statements pasted into a text box by your users is a bad idea. Suffice to say it is a very bad idea; especially if your application is run with higher privileges. In my case, these pasted queries are also persisted in the database if a user with low rights passed a dangerous query someone with higher rights could come across it in the future causing it to be executed.
I needed to find an alternative; I contemplated a couple of things:
- A complicated Regular Expression (RegEx)
- Wrapping the execution in a BEGIN TRANSACTION and ROLLBACK TRANSACTION.
- Running the query under a low (db_reader only) privilege account
Whichever way I looked at it the options didn’t seem great, and I thought there must be an alternative. It turns out there is!