Was this page helpful?
Additional feedback?
1500 characters remaining
Export (0) Print
Expand All

Building Statements at Run Time

Most Microsoft SQL Server 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 noteSecurity Note

    Using the EXECUTE statement to execute a string facilitates SQL injection attacks. We recommend that you use sp_executesql with parameters instead.

Was this page helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

© 2015 Microsoft