declare @tablename varchar(64), @columnname varchar(64) select @tablename = 'Categories', @columnname = 'CategoryName'...
exec ('select ' + @columnname + ' from ' + @tablename)
You may consider using sp_executesql which accomplishes the same, but the Query Optimizer is more likely to re-use the execution plan if only the parameters change. Please see Books Online for some detailed examples. Be aware that using dynamic SQL while very flexible may not be very efficient in some cases. Look the query plans the optimizer generates and compare the exec statement and sp_executesql's performance.
Dig Deeper on SQL Server Stored Procedures
Related Q&A from Joe Toscano
Migrate DTS packages to SQL Server Integration Services with Migration Wizard and deploy SSIS packages in SQL 2005. Learn how to access DTS Designer ... Continue Reading
Can I call triggers in stored procedures or vice versa? Continue Reading
I have a table, let's call it AlarmTriggers and it has a Boolean field pulled into it. When my software writes to it the table doesn't set the field ... Continue Reading