Business Intelligence and Analytics
Executing dynamic SQL in a procedure
In many cases, it is necessary to derive the column name of a query at runtime.
Here's how to do that, in a compiled stored procedure. Note that this is a good method
to use when you want the optimizer to re-process your query at every execution.
-- executing dynamic SQL, in a stored proc
declare @sqlcmd varchar(999),
select @monthcolumn = 'sept_sales'
select @sqlcmd =
'update sales_report set ' + @monthcolumn + ' = 5200 ' +
'where salesrep_id = 25 '
if @@error > 0
raiserror 99999 'Error ocurred during report dynamic SQL exec'
Get the latest Rocket99 news and tech tips via