Professional Documents
Culture Documents
DYNAMIC SQL
We’ve already seen that you can use EXEC to run a stored procedure. However, you can also use
the same command to run any valid SQL enclosed in parentheses:
Purists programmers wouldn’t touch dynamic SQL with a bargepole. Here’s why:
Problem Explanation
SQL injection If you build up a long SQL statement to execute, how do you know what it’s going to
do? This is especially the case when the statement is getting parameters from a
website. Malicious users frequently try to input semi-colons into web forms, hoping to
end your SQL statement being built up behind the scenes and begin their own!
Syntax Because the SQL statement you’re constructing is in a text string, there’s no way that
Management Studio can parse it to check that it makes sense.
Speed For the same reason, SQL Server can’t optimise SQL contained in a text string, as it
would do for the same query normally.
Wise Owl’sAdvanced
Hint Hint
You can mitigate to some extent all these disadvantages by using sp_executesql to run your dyna
The procedure below allows you to run any select command against any table:
-- run it!
EXEC(@sql)
Finally, the procedure executes the command which it’s painstakingly built up to
show the list of genres in genre name order: