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
Getting an error when importing data from an Excel spreadsheet to SSIS in SQL Server 2005? Try lining up data types in Excel and SSIS so they match.continue reading
Is there a query to search text in a SQL Server DTS package? SQL Server expert Joe Toscano explains which database objects can be viewed.continue reading
Convert SQL Server 2000 DTS packages to SQL Server 2005 with this advice and also see how to overwrite data.continue reading
Have a question for an expert?
Please add a title for your question
Get answers from a TechTarget expert on whatever's puzzling you.