Building Statements at Run Time
Most Microsoft SQL Server 2005 applications that have to dynamically build SQL statements at run time do so before calling a database API function or method to execute the statement. For example, a C-language application using ODBC can dynamically build one or more SQL statements into a character array, then pass that array to the ODBC SQLPrepare or SQLExecDirect functions.
Transact-SQL supports the following methods of building SQL statements at run time in Transact-SQL scripts, stored procedures, and triggers:
Use the sp_executesql system stored procedure to execute a Unicode string. sp_executesql supports parameter substitution similar to the RAISERROR statement.
Use the EXECUTE statement to execute a character string. The EXECUTE statement does not support parameter substitution in the executed string.
Security Note: Using the EXECUTE statement to execute a string facilitates SQL injection attacks. We recommend that you use sp_executesql with parameters instead.