Dynamic SQL is executable with the EXEC / EXECUTE statement. It takes one string parameter.
declare @tableName as varchar
set @tableName = 'Orders'
execute ('select * from [' + @tableName +']')
You can also execute dynamic SQL with the built in sp_executesql store procedure. This can take multiple
parameters. The first parameter is the dynamic SQL statement. The next N are variable definitions for the
dynamic SQL, and the next N are the values for variables.
exec sp_executesql 'select * from orders where orderid=@orderid' , '@orderid int' , 10248
Please sign in to leave a comment.