Dynamic SQL (passing table name as parameter)

Well, firstly you’ve omitted the ‘+’ from your string. This way of doing things is far from ideal, but you can do

DECLARE @SQL varchar(250)
SELECT @SQL = 'SELECT * FROM ' + QuoteName(@Alias)
Exec(@SQL)

I’d strongly suggest rethinking how you do this, however. Generating Dynamic SQL often leads to SQL Injection vulnerabilities as well as making it harder for SQL Server (and other DBs) to work out the best way to process your query. If you have a stored procedure that can return any table, you’re really getting virtually no benefit from it being a stored procedure in the first place as it won’t be able to do much in the way of optimizations, and you’re largely emasculating the security benefits too.

Leave a Comment