Executing dynamically generated SQL inside SQL can be a cause of all the same problems as unparameterized SQL, including SQL injection and performance (query plan cache misses).
It looks like you’re executing SQL that you’ve composed dynamically. This could be safe, but: you should ideally use sp_executesql, taking
care to correctly fully parameterize any inputs.
This is a complex topic; please consult the SQL documentation carefully, as incorrect usage may present a security vulnerability.
Bad:
exec ('select * from Customers where Name = ''' + @s + '''');
Good:
exec sp_executesql
N'select * from Customers where Name = @name', -- parameterized SQL to execute
N'@name nvarchar(100)', -- parameter declarations (comma-delimited)
@s; -- arguments (comma-delimited)
Note that rather than compose the value of @s into SQL directly (with predictable results) , we’re
leaving the query parameterized (select * from Customers where Name = @name'), passing the value @s as an argument. Note
also that the parameter names inside the executed query (@name in this case) do not need to match.