To continue reading for free, register below or login
To read more you must become a member of SearchSQLServer.com
');
// -->

Try looking into using dynamic SQL. The simplest would be to pass the table/column(s) as parameters and using the exec command to execute a Transact-SQL command you construct. Below is an example where I use local variables to construct a statement that retrieves data from a table in the Northwind database. You will notice that by using exec (SQL command), you can dynamically construct the SQL command. For complex commands I've used another local variable such as @sqlcmd varchar(2048) to hold the actual command. Below is a simple example:
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.
|