Export (0) Print
Expand All

Building Statements at Run Time

SQL Server 2008 R2

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.

Community Additions

© 2016 Microsoft