Execute a character string
execute (string)
executes the value of a
string
is executed as (or in) a
batch.
Note: the parentheses are required.
declare
@db_name varchar(20) = db_name(),
@table_name varchar(20) = 'a_table';
execute (
' use ' + @db_name +
' create table ' + @table_name + '(id integer)'
)
Execute a stored procedure
When executing a
stored procedure, the parameters must not be enclosed in parentheses. In fact, there are no parentheses allowed because with parentheses, SQL Server tries to execute a
character string.
create procedure greet_planet (
@planet varchar(20) = 'world'
)
as
print('Hello ' + @planet);
go
execute greet_planet
execute greet_planet 'Mars'
execute greet_planet @planet = 'Jupiter'
--
-- Cannot use paranthesis when execute stored procedure:
--
-- execute greet_planet(@planet = 'Saturn')
drop procedure greet_planet;